开发者

AddRange/concat functionality inside a lambda Select expression

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜