程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> LINQ Samples(Custom Sequence Samples)

LINQ Samples(Custom Sequence Samples)

編輯:.NET實例教程

Combine

This sample calculates the dot product of two integer vectors. It uses a user-created sequence Operator, Combine, to calculate the dot product, passing it a lambda function to multiply two arrays, element by element, and sum the result.

public static class CustomSequenceOperators
{
    public static IEnumerable Combine(this IEnumerable first, IEnumerable second, Func func) {
        using (IEnumerator e1 = first.GetEnumerator(), e2 = second.GetEnumerator()) {
            while (e1.MoveNext() && e2.MoveNext()) {
                yIEld return func(e1.Current, e2.Current);
            }
        }
    }
}

public void Linq98() {            
    int[] vectorA = { 0, 2, 4, 5, 6 };
    int[] vectorB = { 1, 3, 5, 7, 8 };
    
    int dotProduct = vectorA.Combine(vectorB, (a, b) => a * b).Sum();
    
    Console.WriteLine("Dot product: {0}", dotProduct);
}

Result

Dot product: 109

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved