简体   繁体   中英

From where arguments are passed to parameters of a lambda expression that is used within PLINQ?

I was working with the below C# code:

    //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();                                
    }

//Output word1,0 word2,1

Question: Above codes works fine. On executing the code, the lamba expression within "Select" query operator, returns an instance of custom struct "IndexedWord". Parameters of the expression receive argument values from wordToTest[] array. For example, if parameter "word" is passed the value "word1", then the parameter "index" is passed the corresponding index position of "word1" in the wordToTest[] array. Im not able to understand exactly at which point of the query(may be internally) this extraction and passing of arguments to the lambda expression occurs. How are the data and its index position of the wordsToTest[] array are extracted and passed to the parameters of the lamba expression? What causes this extraction? Kindly clarify on this. Thank you.

Did you hear something about parallel programming in c#? Its just the same, only with queries. The query occurs parallely with the main method.

"Select" method is the one that extracts each data value and its respective index value from the source array wordsToTest[].

The function call:

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

invokes the constructor:

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

Above mentioned Select() method belongs to Enumerable class. For further details please refer to below mentioned link: https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM