C# 如何使用LINQ右折?

C# 如何使用LINQ右折?,c#,linq,fold,C#,Linq,Fold,使用LINQ,我们可以通过聚合对列表执行以下操作: var numbers = new[] { 1, 2, 3, 4 }; var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8 var value = numbers.Reverse().Aggregate((a, b) => a - b); 使用LINQ执行右折叠是否有类似的方法 var value = numbers.Aggrega

使用LINQ,我们可以通过
聚合
对列表执行以下操作:

var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8
var value = numbers.Reverse().Aggregate((a, b) => a - b);
使用LINQ执行右折叠是否有类似的方法

var value = numbers.Aggregate(???); // 1 - (2 - (3 - 4)) == -2

右折叠本质上是从右向左折叠。我们可以复制一个右折叠,如果我们
首先反转
可枚举项,然后通过
聚合
执行左折叠:

var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8
var value = numbers.Reverse().Aggregate((a, b) => a - b);

作为一种扩展方法:

public static TSource RightFold<TSource>(this IEnumerable<TSource> source,
    Func<TSource, TSource, TSource> func)
{
    return source.Reverse().Aggregate(func);
}

右折叠本质上是从右向左折叠。我们可以复制一个右折叠,如果我们
首先反转
可枚举项,然后通过
聚合
执行左折叠:

var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8
var value = numbers.Reverse().Aggregate((a, b) => a - b);

作为一种扩展方法:

public static TSource RightFold<TSource>(this IEnumerable<TSource> source,
    Func<TSource, TSource, TSource> func)
{
    return source.Reverse().Aggregate(func);
}

如果您已经在使用check
AggregateRight
方法

如果您已经在使用check
AggregateRight
方法

,您可以在该方法之后重新进行CSE和聚合<代码>数字.Reverse().Aggregate((a,b)=>a-b)你不能既吃蛋糕又吃东西it@NikhilAgrawal我在谷歌上搜索了这篇文章的标题,但什么也没有(显著地)出现,所以我想我会和大家分享我的解决方案。你可以在那之后重新思考和聚合<代码>数字.Reverse().Aggregate((a,b)=>a-b)你不能既吃蛋糕又吃东西it@NikhilAgrawal我在谷歌上搜索了这篇文章的标题,但没有(显著地)显示任何内容,所以我想我会与大家分享我的解决方案。这不太正确,请使用3个参数进行尝试:你的函数给出
(3-2)-1==0
,但OP正在寻找
1-(2-3)==2
。您需要将参数的顺序切换到
func
返回source.Reverse().Aggregate((a,b)=>func(b,a))这不太正确,请尝试使用3个参数:您的函数给出
(3-2)-1==0
,但OP正在寻找
1-(2-3)==2
。您需要将参数的顺序切换到
func
返回source.Reverse().Aggregate((a,b)=>func(b,a))