1
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();
fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253

2 Answers2

9

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
  • 155,851
  • 29
  • 291
  • 343
1

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900