Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct in linq?

Tags:

c#

linq

distinct

I am wondering how can I achieve this?

I want to get only distinct names from a collection of objects

MyObject a = new Object();
a.Name = 'One';
a.Value = '10';


MyObject b = new Object();
b.Name = 'One';
b.Value = '15';


MyObject c = new Object();
c.Name = 'Two';
c.Value = '10';

So I want to get only back the name. I don't care about the value in this case just the name.

So I tried

//add all the objects to a collection.

myCollection.Disinct()..Select(x => new MyClassToStore() {Text = x.Name, Value = x.Name}).ToList());

However I need to do distinct at the property level not at the object level. So I want back "One" and "Two". Right now I get "One", "One" and "Two" back.

I see a library called morelinq but I not sure if I should use it as it still in beta and does not seem to be developed on anymore.

Plus a whole library for one extract query I am not sure if it is worth it.

like image 594
chobo2 Avatar asked Apr 09 '11 21:04

chobo2


People also ask

What does distinct do 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).

Why distinct is not working in LINQ?

Yes, it doesn't work as expected! This is because the Distinct method uses the default equality comparer to compare the values under the hood. Since we are dealing with reference type object, the Distinct() method will treat the values as unique even if the property values are the same.

Is distinct a set operator?

The Distinct operator returns the set which does not contain duplicate values. Or in other words, we can say that this operator removes all the duplicate values from the set or collection and return a set or collection which contain unique or dissimilar values.


2 Answers

Maybe something like this can help?

var distinctItems = items
     .GroupBy(x => x.PropertyToCompare)
     .Select(x => x.First());
like image 200
Marino Šimić Avatar answered Oct 21 '22 21:10

Marino Šimić


This populates both the Text and Value fields:

   myCollection.Select(x => x.Name).Distinct()
      .Select(x => new MyClassToStore { Text = x, Value = x }).ToList();
like image 41
PHeiberg Avatar answered Oct 21 '22 20:10

PHeiberg