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).
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().
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.
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.
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()
This should work for you.
var result = list.Select(x => x.GroupId).Distinct().Count();
First you are selecting out all the GroupId
s. Then you are filtering them to be distinct. Finally you are getting the count of those values.
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