The problem is your Idnavio is a unique value. The Enumerable.Distinct()
uses Object methods to do its job. In the case of anonymous type the compiler will override the Object.Equals()
and the Object.GetHashCode()
and will compare all values of your type. Since your Idnavio will always have different values among themselves, the same will always be different.
The simple solution would be a Iequalitycomparer, but he is not an employee since you have an anonymous type and only using reflection you could know which properties will participate in the comparison, something similar to the one exemplified here:
https://www.codeproject.com/Articles/94272/A-Generic-IEqualityComparer-for-Linq-Distinct
So the best solution, in my humble opinion, is for you to create a Command class and overwrite Object.Equals()
and Object.GetHashCode()
, so implementing Distinctby would be much simpler:
public class NavioComparer : IEqualityComparer<NavioCommand>
{
public bool Equals(NavioCommand first, NavioCommand second)
{
return first.Navio.Equals(second.Navio);
}
public int GetHashCode(NavioCommand obj)
{
return obj.Navio.GetHashCode();
}
}
Other addenda:
- Morelinq’s Distinctby employee, however he works with Ienumerable, not Iqueryable, so his Distinct would run in memory, not in the database.
- You could also implement your own Distinctby that accepts a Iqueryable (LINQ example).
What’s the matter? He keeps bringing duplicates?
– Gabriel Coletta
@Gabrielcoletta Continues to bring duplicate.
– Samuel Renan Gonçalves Vaz
Idnavio is a primary key?
– Gabriel Coletta
@Gabrielcoletta Actually this select is based on a View of the bank that has several Ids, one of them is the Ship Id. Could that be the problem ? for being a view ?
– Samuel Renan Gonçalves Vaz
theoretically not, the problem is if it is a primary key. Can I say it is? If it is already know the problem
– Gabriel Coletta
@Gabrielcoletta Yes, it is a primary key.
– Samuel Renan Gonçalves Vaz
@samuelrvg You want to distinguish by a property or by the two?
– Jéf Bueno
@LINQ by Ship Id only, but if possible by the two also looks interesting.
– Samuel Renan Gonçalves Vaz
You know that one Id is always different from the other, right? That’s the main problem of your Distinct().
– Gabriel Coletta