背景介绍
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;}
}