Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the number of distinct property values in List<T> using LINQ in C#

In a list List<MyClass> ListOfMyClasses, how can one get the how many distinct GroupId property values there are using LINQ?

public class MyClass
{
     public int GroupId;
}

For example let's say we have this list:

ListOfMyClasses: {MyClass1 (GroupId = 1), MyClass2 (GroupId = 3), MyClass3 (GroupId = 1)}

Here we should get the result as 2 (Two distinct numbers for GroupId).

like image 285
Vahid Avatar asked Jun 01 '16 20:06

Vahid


People also ask

Where is distinct in LINQ?

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). IEnumerable<data type> result = numbers. Distinct(); Here is a sample code showing the implementation of C# LINQ Distinct().

Why distinct is not working in Linq?

LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


2 Answers

Here is one way to do it using Distinct:

ListOfMyClasses.Select(t => t.GroupId).Distinct().Count()

Or you can also use GroupBy:

ListOfMyClasses.GroupBy(t => t.GroupId).Count()
like image 92
sstan Avatar answered Sep 21 '22 00:09

sstan


This should work for you.

var result = list.Select(x => x.GroupId).Distinct().Count();

First you are selecting out all the GroupIds. Then you are filtering them to be distinct. Finally you are getting the count of those values.

like image 30
Matt Rowland Avatar answered Sep 21 '22 00:09

Matt Rowland