首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 擴展方法進階技巧:改良 Aggregate 擴展方法支援索引 (下)

     編輯:關於C語言

原版 Aggregate 僅提供累加值與當前元素,缺乏索引資訊。反編譯 System.Core.dll 後改良,加入索引參數:

改良版 Aggregate

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

應用範例:間隔求和

int[] nums = {10, 20, 30, 40, 50};
int sum = nums.Aggregate((a, c, i) => a + (i % 2 == 0 ? c : 0)); // 10+30+50=90

極限演算法應用

陣列含 1~n 共 n+1 個元素,唯一重複值查找:

int[] array = {1, 3, 2, 3, 4, 5};
int repeated = array.Aggregate((a, n, i) => a + n - i); // 直接算出重複值

索引參數賦予 Aggregate 全新威力,可替代 Where+Select+Sum 組合,大幅精簡程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved