How does Func Work?

后端 未结 3 1146
悲哀的现实
悲哀的现实 2021-02-05 08:58

I am creating a Distinct extension method where I can pass in the criteria like the following.

persons.Distinct(p => p.Name); 

I got the co

3条回答
  •  [愿得一人]
    2021-02-05 09:23

    When you do this:

    persons.Distinct(p => p.Name);
    

    You're basically creating a function on the fly (using lambda expressions), that looks like this:

    string theFunction(Person p)
    {
        return p.Name;
    }
    

    This is a function that fits the signature of a Func delegate. The Distinct method can take a delegate (basically a function pointer) which it uses to determine whether or not an element is distinct - in your case, only unique strings (returned by the function above) will be considered "distinct" elements. This delegate is run on each element of your "persons" enumerable, and the results of those functions are used. It then creates a sequence (IEnumerable) from those elements.

提交回复
热议问题