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>
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With