开发者

AddRange/concat functionality inside a lambda Select expression

开发者 https://www.devze.com 2023-01-20 12:31 出处:网络
class Foo { int PrimaryItem; bool HasOtherItems; 开发者_StackOverflow社区IEnumerable<int> OtherItems;
class Foo
{
    int PrimaryItem;
    bool HasOtherItems;
开发者_StackOverflow社区    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();


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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消