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).
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.