i have a C# application in which i'd like to get from a List
of Project objects , another List which contains distinct objects.
i tried this
List<Project> model = notre_admin.Get_List_Project_By_Expert(u.Id_user);
if (model != null) model = model.Distinct().ToList();
The list model still contains 4 identical objects Project
.
What is the reason of this? How can i fix it?
Here's an answer from basically the same question that will help.
Explanation:
Credits to @Rex M.
The object's reference aren't equal. If you want to be able to do that on the entire object itself and not just a property, you have to implement the IEqualityComparer or IEquatable<T>.
How do you define identical? You should override
Equals
inProject
with this definition (if you overrideEquals
also overrideGetHashCode
). For example:Otherwise you are just checking reference equality.
or you can write like this
Isn't simpler to use one of the approaches shown below :) ? You can just group your domain objects by some key and select FirstOrDefault like below.
More interesting option is to create some Comparer adapter that takes you domain object and creates other object the Comparer can use/work with out of the box. Base on the comparer you can create your custom linq extensions like in sample below. Hope it helps :)
Custom comparer adapter:
Custom linq extension (definition of DistinctBy extension method):
Definition of domain object used in test case:
You need to define "identical" here. I'm guessing you mean "have the same contents", but that is not the default definition for classes: the default definition is "are the same instance".
If you want "identical" to mean "have the same contents", you have two options:
IEqualityComparer<Project>
) and supply that as a parameter toDistinct
Equals
andGetHashCode
onProject
There are also custom methods like
DistinctBy
that are available lots of places, which is useful if identity can be determined by a single property (Id
, typically) - not in the BCL, though. But for example:With, for example: