views:

59

answers:

2
class Foo
{
    int PrimaryItem;
    bool HasOtherItems;
    IEnumerable<int> OtherItems;
}

List<Foo> fooList;

How do I get a list of all item ids referenced inside fooList?

var items = fooList
             .Select(
              /*
                f => f.PrimaryItem;
                if (f.HasOtherItems)
                    AddRange(f => f.OtherItems)
              */  
              ).Distinct();
+5  A: 

Use SelectMany and have it return a concatenated list of the PrimaryItem and OtherItems (if they are present):

var result = fooList
    .SelectMany(f => (new[] { f.PrimaryItem })
        .Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
    .Distinct();
Fredrik Mörk
+1  A: 

As a slight variation:

var items = fooList.Select(i => i.PrimaryItem).Union(
      fooList.Where(foo => foo.HasOtherItems).SelectMany(foo => foo.OtherItems));

This takes the set of PrimaryItem, and (where HasOtherItems is set) concatenates the combined set of OtherItems. The Union ensures distinct.

Marc Gravell
nice solution :)
fearofawhackplanet