在 C# 中使用 LINQ 获取 List<T> 中不同 属性 值的数量
Get the number of distinct property values in List<T> using LINQ in C#
在列表 List<MyClass> ListOfMyClasses
中,如何使用 LINQ 获得有多少个不同的 GroupId
属性 值?
public class MyClass
{
public int GroupId;
}
例如,假设我们有这个列表:
ListOfMyClasses: {MyClass1 (GroupId = 1), MyClass2 (GroupId = 3), MyClass3 (GroupId = 1)}
这里我们应该得到结果 2(GroupId 有两个不同的数字)。
这是使用 Distinct
的一种方法:
ListOfMyClasses.Select(t => t.GroupId).Distinct().Count()
或者你也可以使用GroupBy
:
ListOfMyClasses.GroupBy(t => t.GroupId).Count()
这应该适合你。
var result = list.Select(x => x.GroupId).Distinct().Count();
首先,您要选择所有 GroupId
。然后你过滤它们以区分它们。最后,您将获得这些值的计数。
此外,我只想分享一些我在所有项目中使用的扩展,它也解决了你的任务
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));
}
}
它允许你写ListOfMyClasses.DistinctByProperty(x => x.GroupId).Count()
在列表 List<MyClass> ListOfMyClasses
中,如何使用 LINQ 获得有多少个不同的 GroupId
属性 值?
public class MyClass
{
public int GroupId;
}
例如,假设我们有这个列表:
ListOfMyClasses: {MyClass1 (GroupId = 1), MyClass2 (GroupId = 3), MyClass3 (GroupId = 1)}
这里我们应该得到结果 2(GroupId 有两个不同的数字)。
这是使用 Distinct
的一种方法:
ListOfMyClasses.Select(t => t.GroupId).Distinct().Count()
或者你也可以使用GroupBy
:
ListOfMyClasses.GroupBy(t => t.GroupId).Count()
这应该适合你。
var result = list.Select(x => x.GroupId).Distinct().Count();
首先,您要选择所有 GroupId
。然后你过滤它们以区分它们。最后,您将获得这些值的计数。
此外,我只想分享一些我在所有项目中使用的扩展,它也解决了你的任务
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));
}
}
它允许你写ListOfMyClasses.DistinctByProperty(x => x.GroupId).Count()