在C#中,C ++ std::partial_sum的最佳等价物是什么?
答案 0 :(得分:8)
该操作似乎是组合map(aka Select)和reduce(aka Aggregate)操作的弱版本,仅限于二进制操作。我们可以做得更好!
public static IEnumerable<R> MyAggregate<T, R>(
this IEnumerable<T> items,
R seed,
Func<T, R, R> mapper)
{
R current = seed;
foreach(T item in items)
{
current = mapper(item, current);
yield return current;
}
}
现在你想要的功能只是一个特例:
static IEnumerable<int> PartialSum(this IEnumerable<int> items) =>
items.MyAggregate(0, (i, s) => s + i);
评论员Tom Blodget指出,这要求总和操作具有身份;怎么样,如果你没有?在这种情况下,您必须放弃使sum类型与summand类型不同的能力:
public static IEnumerable<T> PartialSum<T>(
this IEnumerable<T> items,
Func<T, T, T> sum)
{
bool first = true;
T current = default(T);
foreach(T item in items)
{
current = first ? item : sum(current, item);
first = false;
yield return current;
}
}
你可以使用它
myints.PartialSum((i, s) => i + s);
答案 1 :(得分:-1)
试试这个:
int[] values = new[] { 1, 2, 3, 4 };
var result = values.Select ((x, index) => values.Take (index + 1).Sum ());
结果:1, 3, 6, 10
但如果你关心表现,最好自己编写方法。
修改强>
public static IEnumerable<T> MyAggregate<T> (this IEnumerable<T> items, Func<T, T, T> mapper)
{
bool processingFirstElement = true;
T accumulator = default (T);
foreach (T item in items)
{
if (processingFirstElement)
{
processingFirstElement = false;
accumulator = item;
}
else
{
accumulator = mapper (accumulator, item);
}
yield return accumulator;
}
}
现在:
int[] values = new int[] { 1, 2, 3, 4 };
var result = values.MyAggregate ((accumulator, item) => accumulator + item).ToList ();