I would like to get distinct objects from a list. I tried to implement IEqualityComparer
but wasn\'t successful. Please review my code and give me an explanation fo
Try this:
var distinct = collection.Distinct(new MessageComparer());
Then use distinct
for anything after that.
It looks like you're forgetting the immutable nature of IEnumerable<>
. None of the LINQ methods actually change the original variable. Rather, they return IEnuerable
s which contain the result of the expression. For example, let's consider a simple List
with the contents { "a", "a", "b", "c" }
.
Now, let's call original.Add("d");
. That method has no return value (it's void
). But if we then print out the contents of original
, we will see { "a", "a", "b", "c", "d" }
.
On the other hand, let's now call original.Skip(1)
. This method does have a return value, one of type IEnumerable
. It is a LINQ expression, and performs no side-effecting actions on the original collection. Thus, if we call that and look at original
, we will see { "a", "a", "b", "c", "d" }
. However, the result from the method will be { "a", "b", "c", "d" }
. As you can see, the result skips one element.
This is because LINQ methods accept IEnumerable
as a parameter. Consequently, they have no concept of the implementation of the original list. You could be passing, via extension method, a ReadOnlyCollection
and they would still be able to evaluate through it. They cannot, then, alter the original collection, because the original collection could be written in any number of ways.
All that, but in table form. Each lines starts with the original { "a", "a", "b", "c" }
:
Context Example function Immutable? Returned Value Collection after calling
Collection Add("d") No (void) { "a", "a", "b", "c", "d" }:
LINQ Skip(1) Yes { "a", "b", "c" } { "a", "a", "b", "c" }: