lambda Select表达式中的AddRange/concat功能

fea*_*net 1 c# linq lambda select addrange

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

List<Foo> fooList;
Run Code Online (Sandbox Code Playgroud)

如何获取内部引用的所有项ID的列表fooList

var items = fooList
             .Select(
              /*
                f => f.PrimaryItem;
                if (f.HasOtherItems)
                    AddRange(f => f.OtherItems)
              */  
              ).Distinct();
Run Code Online (Sandbox Code Playgroud)

Fre*_*örk 7

使用SelectMany并将其返回的一个拼接列表PrimaryItemOtherItems(如果存在的话):

var result = fooList
    .SelectMany(f => (new[] { f.PrimaryItem })
        .Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
    .Distinct();
Run Code Online (Sandbox Code Playgroud)