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
Func<T, TResult>
defines a function that accepts one parameter (of type T) and returns an object (of type TResult).
In your case, if you want a function that takes a Person object and returns a string...you'd want
Func<Person, string>
which is the equivalent of:
string Function(Person p)
{
return p.Name;
}
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<Person,String>
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<Person>
) from those elements.
You are getting back the distinct People, under the assumption that two People are the same if they have the same name
If you want a distinct set of names, you can use this:
IEnumerable<String> names = persons.Select(p => p.Name).Distinct();