7

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).

Vahid
  • 5,144
  • 13
  • 70
  • 146

3 Answers3

16

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()
sstan
  • 35,425
  • 6
  • 48
  • 66
4

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.

Matt Rowland
  • 4,575
  • 4
  • 25
  • 34
0

In addition, just want to share some extension which I use in all my projects and it also solves your task

public class EqualityComparer<TEntity, TProperty>: IEqualityComparer<TEntity>
{
    private readonly Func<TEntity, TProperty> _property;

    public EqualityComparer(Func<TEntity, TProperty> property)
    {
        _property = property;
    }

    public bool Equals(TEntity x, TEntity y)
    {
        return _property(x).Equals(_property.Invoke(y));
    }

    public int GetHashCode(TEntity obj)
    {
        return _property(obj).GetHashCode();
    }
}

public static class Extensions
{
    public static IEnumerable<T> DistinctByProperty<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propertyFunc)
    {
        return source.Distinct(new EqualityComparer<T, TProp>(propertyFunc));
    }
}

It allows you to write ListOfMyClasses.DistinctByProperty(x => x.GroupId).Count()

Ivan Bianko
  • 1,749
  • 15
  • 22