C#中IEnumerable.Aggregate()的简单使用

背景介绍

IEnumerable<T>.Aggregate()在LINQ使用中好像很不起眼,但我个人认为这是十分实用并且强大的,支持自定义聚合操作,方法定义中的Func包含3个TSource参数,分别为下一个执行聚合的元素,当前聚合的元素,返回的元素。

代码如下:

        static void Main(string[] args)
        {


            List<Phone> PhoneLists = new List<Phone>()
            {
                new Phone { Country = "中国", City = "北京", Name = "小米" },
                new Phone { Country = "中国",City = "北京",Name = "华为"},
                new Phone { Country = "中国",City = "北京",Name = "联想"},
                new Phone { Country = "中国",City = "台北",Name = "魅族"},
                new Phone { Country = "日本",City = "东京",Name = "索尼"},
                new Phone { Country = "日本",City = "大阪",Name = "夏普"},
                new Phone { Country = "日本",City = "东京",Name = "松下"},
                new Phone { Country = "美国",City = "加州",Name = "苹果"},
                new Phone { Country = "美国",City = "华盛顿",Name = "三星"},
                new Phone { Country = "美国",City = "华盛顿",Name = "HTC"}

            };

            Phone phone = PhoneLists.Aggregate((next, now) =>
            {
                if (now.Country.Equals("美国"))
                {
                    next.City += now.City;
                    return next;
                }
                else
                {
                    return now;
                }
            });
            Console.WriteLine($"{phone.Country} - {phone.City} - {phone.Name}");
            Console.Read();
        }

 执行结果如下图所示:

另外附上此方法的源代码:

public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func)
{
     using (IEnumerator<TSource> enumerator = source.GetEnumerator())
     {
          enumerator.MoveNext();
          TSource current = enumerator.Current;
          while (enumerator.MoveNext())
          current = func(current, enumerator.Current);
          return current;
      }
}

 

发布了106 篇原创文章 · 获赞 4 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览