Aggregate
让您提供一个自定义函数来运行 IEnumerable<T>
并返回 T
。
Sum
让您拉一个 int
使用自定义函数从每个元素中提取出来,然后将它们全部添加到一起。
但是如果我想做这样的事情怎么办:
struct S
{
public int i;
public int j;
}
int Aggregate(IEnumerable<S> data)
{
int ret = 0;
foreach(x in data)
{
ret ^ = Math.Max(x.i,x.j);
}
return ret;
}
就像我想使用指定的函数聚合到指定的类型一样。 LINQ 是否提供此功能还是必须组合多个 LINQ 操作?
最佳答案
您可以使用 LINQ 的 Aggregate
之一执行此操作的函数:
Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)
例如:
var aggregate = data.Aggregate(0, (acc, cur) => acc ^ Math.Max(cur.i, cur.j));
如 docs 中所述:
Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.
关于c# - 使用LINQ,如何将集合聚合为指定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61389276/