0

As a LINQ-beginner I wonder why nobody mentioned in Implementing IEqualityComparer<T> for comparing arbitrary properties of any class (including anonymous) that the query actually has to be carried out to get the results. In other words, just calling
IEnumerable<Person> people = ... ; // some database call here var distinctPeople = people.Distinct(new PropertyComparer<Person>("FirstName"));
will not trigger the execution of the specific Equals(Tx, Ty) and GetHashCode(T obj) methods in the PropertyComparer.

The message "Expanding the Results View will enumerate the IEnumerable" (in the Debugger) gave me the hint. Now, could I proceed with something like foreach (var dp in distinctPeople) to get the results?

Community
  • 1
  • 1
  • 4
    What is the question? How to use Distinct on IEnumerable? – Jordy van Eijk Sep 23 '14 at 16:48
  • 3
    And as for why no-one happened to mention it - pretty much everything in LINQ is lazy. There's nothing special about `Distinct` here. There's no point in mentioning that in every single answer to every single question about LINQ. – Jon Skeet Sep 23 '14 at 16:48
  • Feels opinion based/too broad to me. This may be better question to meta - how deep one is expected to explain particular solution. I.e. whether targeting complete beginners is a goal or one should stop explanation on current level of calls. – Alexei Levenkov Sep 23 '14 at 17:26
  • @JordyvanEijk: I was working on the `equals` and `GetHashCode` methods and did not understand why they were not called when calling `people.Distinct(new comparer("Firstname"))`. Now things got clearer. – BlackForest18 Sep 24 '14 at 06:49

1 Answers1

0

This has nothing at all to do with the IEqualityComparer. It is entirely based on the method you're providing it to, in this case, Distinct. Distinct, along with all of the LINQ methods that return an IEnumerable, defer execution as much as possible, only performing the work that they need to compute the results when they actually need to do so.

Servy
  • 202,030
  • 26
  • 332
  • 449