Symbols count in article: 515Reading time: 3 mins.
When using Linq on your Entity Framework objects, you often need to distinct your query results. Therefore you need to implement an IEqualityComparer for the more advance scenario’s. For example if you want to distinct on a specific property, or maybe on multiple properties. However this forces you to write lots of infrastructure code to distinct each type.
You probably would end up with several equality compare classes like this.
However there is a solution which will save you the work to write all this classes. You will have to write only two classes. One will contain some extension methods, the other is a DelegateEqualityComparer.
Now you can simply distinct your query by providing a lambda. I tried it on IQueryable, but this doesn’t work. Linq will generate some SQL to do the actual query. We didn’t specified any code that can translate the equality comparer to SQL. If someone figures out how to make it work with IQueryable please let me know.
1 2 3 4 5
_products.Distinct((x, y) => x.Id == y.Id, x => x.Id.GetHashCode()); _products.Distinct((x, y) => x.Price == y.Price, x => x.Price.GetHashCode()); _persons.Distinct((x, y) => x.LastName == y.LastName, x => x.LastName.GetHashCode()); _persons.Distinct((x, y) => x.FirstName == y.FirstName, x => x.FirstName.GetHashCode()); _persons.Distinct((x, y) => x.Address.City == y.Address.City, x => x.Address.City.GetHashCode());