lambda中的addrange/Concat功能选择表达式
题
class Foo
{
int PrimaryItem;
bool HasOtherItems;
IEnumerable<int> OtherItems;
}
List<Foo> fooList;
我如何获得内部引用的所有项目ID的列表 fooList
?
var items = fooList
.Select(
/*
f => f.PrimaryItem;
if (f.HasOtherItems)
AddRange(f => f.OtherItems)
*/
).Distinct();
解决方案
采用 SelectMany
并返回一个串联列表 PrimaryItem
和 OtherItems
(如果存在):
var result = fooList
.SelectMany(f => (new[] { f.PrimaryItem })
.Concat(f.HasOtherItems ? f.OtherItems : new int[] { }))
.Distinct();
其他提示
有点变化:
var items = fooList.Select(i => i.PrimaryItem).Union(
fooList.Where(foo => foo.HasOtherItems).SelectMany(foo => foo.OtherItems));
这是一组 PrimaryItem
, 和(在哪里 HasOtherItems
设置)联合组合 OtherItems
. 。这 Union
确保独特。
不隶属于 StackOverflow