C#中IEnumerableT.Aggregate()的简单使用
生活随笔
收集整理的這篇文章主要介紹了
C#中IEnumerableT.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;} }?
總結
以上是生活随笔為你收集整理的C#中IEnumerableT.Aggregate()的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET Web API 中的属性
- 下一篇: 湖北工业大学计算机专硕学费,2019年湖