-1

I have 2 Lists, one is a class, the other is integers. I am trying to return all ParentID values that exist in one of the Lists Taxonomy property, but not having any success in generating this.

For example:

List<int> theListingCatIDs = new List<int>();
theListingCatIDs = allMemberListings.Select(u => u.Taxonomy.ConvertAll<int>(v => v.ParentID)).Distinct().ToList();

This gives me error saying that it can not convert List<List<int>> to List<int>, But how can I flatten the results to just put them all in a List<int>??

Solomon Closson
  • 6,111
  • 14
  • 73
  • 115
  • possible duplicate of [Linq on a nested List - select all Id's](http://stackoverflow.com/questions/7363730/linq-on-a-nested-list-select-all-ids) – drneel Aug 14 '14 at 02:40
  • It isn't an exact duplicate of that question, but that question and that answer will tell you how to do this. – Matthew Haugen Aug 14 '14 at 02:42
  • And just by the way, you shouldn't be instantiating `theListingCatIDs` to a `List` before you assign it to your LINQ expression. It's not a big deal, but that is creating an unused instance in memory that the GC then has to clean up, with no gain. – Matthew Haugen Aug 14 '14 at 02:47
  • @MatthewHaugen - Thanks, I put it in the global scope of the file instead since I need to use it in an `OnItemDataBound` repeater. Cheers :) – Solomon Closson Aug 14 '14 at 03:22
  • By the way, I have tried searching on SO before posting up this question. Thanks for the helpful links, though, I wasn't quite sure what to search for, and the results I was getting on my searches did not help. – Solomon Closson Aug 14 '14 at 03:31

1 Answers1

3

You can use SelectMany:

var ids = allMemberListings
    .SelecMany(x => x.Taxonomy)
        .Select(x => x.ParentID)
    .Distinct()
    .ToList()

MSDN: http://msdn.microsoft.com/en-us/library/bb534336(v=vs.100).aspx

It flattens the nested lists into a single list of whatever Taxonomy is. You can then use Select as normal to pull out the ParentIDs.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138