2016-09-21 66 views
1

我用下面的C#代碼的工作:從哪裏傳遞參數到PLINQ中使用的lambda表達式的參數?

//Custom structure 
    struct IndexedWord 
    { 
     public string Word; 
     public int Index; 
    } 

    static void Main(string[] args) 
    { 

     string[] wordsToTest = {"word1", "word2"}; 

     var query = wordsToTest 
        .AsParallel() 
        .Select((word, index) => 
        new IndexedWord {Word = word, Index = index});  

     foreach(var structs in query) 
     { 
      Console.WriteLine("{0},{1}", structs.Word,structs.Index); 
     } 

     Console.WriteLine(); 
     Console.ReadKey();         
    } 

//輸出 word1,0 word2,1

問: 上面的代碼工作正常。在執行代碼時,「Select」查詢運算符中的lamba表達式返回一個自定義結構「IndexedWord」的實例。表達式的參數接收來自wordToTest []數組的參數值。例如,如果參數「word」被傳遞值「word1」,則參數「index」被傳遞給wordToTest []數組中的「word1」的對應索引位置。我無法準確理解查詢的哪一點(可能是內部的),這種提取以及將參數傳遞給lambda表達式會發生。如何提取wordsToTest []數組的數據及其索引位置並將其傳遞給lamba表達式的參數?什麼導致這種提取?請在此澄清。謝謝。

回答

1

您是否聽說過有關c#中的並行編程的內容?它只是與查詢相同。查詢與主要方法並行發生。

+0

謝謝。根據你的回答,我能夠解決上述疑問。 –

1

「Select」方法是從源數組wordsToTest []中提取每個數據值及其各自的索引值的方法。

函數調用:

wordsToTest.Select((word, index) => 
        new IndexedWord { Word = word, Index = index }); 

調用構造:

public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source, 
Func<TSource, int, TResult> selector) 

上面提到的選擇()方法屬於枚舉類。詳情請參閱下面提到的鏈接: https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx

謝謝。