Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Distinct based on property of object

Tags:

linq

distinct

Is it possible to get the distinct elements of a List based on a property of the objects in the List?

Someting like: Distinct(x => x.id)

What's not usefull for me is following: .Select(x => x.id).Distinct() because then I would get back a List<int> instead of List<MyClass>

like image 993
Lieven Cardoen Avatar asked Jan 17 '10 20:01

Lieven Cardoen


People also ask

How do you used distinct 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).

How do I get distinct on a single column in LINQ?

Select(x => x. FirstOrDefault()); This will group the table by Text and use the first row from each groups resulting in rows where Text is distinct.

What are LINQ queries in C#?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

That sounds like a grouping construct to me, because you need to decide which of the supposedly identical object you actually want to return

var q = from x in foo
        group x by x.Id into g
        select g.First(); // or some other selection from g

Just because Id is identical across multiple items doesn't mean that the items are identical on other properties, so you need to explicitly decide which item is returned.

like image 131
Mark Seemann Avatar answered Oct 02 '22 14:10

Mark Seemann