C# Enumerable.Aggregate方法

官方doc地址:'https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-5.0#System_Linq_Enumerable_Aggregate__1_System_Collections_Generic_IEnumerable___0__System_Func___0___0___0__',首先,根据字面意思进行理解,Aggregate在英文中表示‘合计,聚合’意思,从这个角度出发,我们进一步探究Aggregate方法的用法,首先看这样一个实例:

        private static void Main(string[] args)
        {
            int[] testArray = new[] {1, 2, 3, 4, 5};
            var aggragateResult = testArray.Aggregate((tempAggregatedVal, next) => tempAggregatedVal += next);
            Console.WriteLine(aggragateResult);
            Console.Read();
        }

在上面的这个实例中,我们将数组testArray中的每一项进行了合并求和,至于Aggravate方法的工作过程 ,我个人根据微软官方doc的理解如下:Arrragate方法的参数是一个func,它会对testArray中除了第一项的每一项调用这个funcfunc第一次执行时,其第一个参数来自于数组中的第一项(作为一个初始的聚合结果值),第二个参数来自于数组中的第二项。当func第二次执行时,其两个参数分别来自于上一次func执行的结果以及数据中的当前遍历项(也就是数组中的第三项),以后每次执行以此类推。当对数组中的最后一项执行完func之后,返回一个对集合数据进行我们自定义聚合过程的聚合值。因此,EnumerableAggregate方法并不只是用来求和(因为聚合过程我们是可以通过这个func进行自定义的),比如我们可以对一句话进行倒置:

        private static void Main(string[] args)
        {
            string testStr = "A B C D E F G";
            string[] strAry = testStr.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
            var aggregateResult = strAry.Aggregate((tempAggregatedVal, next) => next += tempAggregatedVal);
            Console.WriteLine(aggregateResult);
            Console.Read();
        }

上面的打印结果为:GFEDCBA
在上面的使用方式中,我们的数组包含的元素(或者宏观上说IEnumerable<T>)是什么类型,那么对其调用Aggregate方法之后返回的聚合结果就是就是什么类型(也就是IEnumerable<T>中的T类型),但是,Aggregate方法还有另外的两种重载,上面只是其中的一种重载。
在微软的官方doc中,Aggregate方法还有这样一种重载(注意它的聚合结果是可以与集合中包含的数据类型不同的)

public static TAccumulate Aggregate<TSource,TAccumulate> (this System.Collections.Generic.IEnumerable<TSource> sour
ce, TAccumulate seed, Func<TAccumulate,TSource,TAccumulate> func);

以下是对上面这种重载的使用介绍:

        private static void Main(string[] args)
        {
            int[] testArray = new[] {1, 2, 3, 4, 5};
            string aggragateResult = testArray.Aggregate(string.Empty,(tempAggregatedVal, next) => tempAggregatedVal += next.ToString());
            Console.WriteLine($"聚合结果为{aggragateResult}");
        }

在这种重载中,我们可以显式指定初始的聚合结果值(也就是指定对上例中数组中的各项进行聚合操作前tempAggregatedVal的初始值),同时因为我们已经显式指定了初始的聚合结果值,因此和之前的例子不同的地方就在于数组中的第一项不再作为初始的聚合结果值,同时数组的聚合操作是针对数组中的第一项开始的(之前都是从第二项开始的,第一项作为初始的聚合操作结果值),在上面的例子中,最后的打印结果是一个字符串类型的‘12345’。在这种重载下,要判断Aggregate方法的返回结果类型可以根据Aggregate方法的第一个参数类型进行判断(因为从方法签名来看其与Aggregate方法的返回类型是一样的)。

posted @ 2021-03-10 12:03  moon3  阅读(145)  评论(0编辑  收藏  举报