Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Distinct with LINQ and Objects

Tags:

linq

distinct

Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class containing a category and country (both enums). The Distinct isn't working now.

What am I doing wrong?

like image 206
Tim Almond Avatar asked Dec 14 '10 11:12

Tim Almond


People also ask

How does distinct work in LINQ?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

Does distinct preserve order?

Java Stream distinct() MethodIf the stream is ordered, the encounter order is preserved. It means that the element occurring first will be present in the distinct elements stream.

What is LINQ in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.


1 Answers

I believe this post explains your problem: http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

The content of the above link can be summed up by saying that the Distinct() method can be replaced by doing the following.

var distinctItems = items
       .GroupBy(x => x.PropertyToCompare)
       .Select(x => x.First());
like image 145
Stilgar Avatar answered Sep 18 '22 03:09

Stilgar