使用LINQ在C#中获取List<T>中不同属性值的数量

7
在一个列表 List<MyClass> ListOfMyClasses 中,如何使用LINQ获取有多少个不同的 GroupId 属性值?
public class MyClass
{
     public int GroupId;
}

例如,假设我们有以下列表:
ListOfMyClasses: {MyClass1 (GroupId = 1), MyClass2 (GroupId = 3), MyClass3 (GroupId = 1)}

在这里,我们应该得到结果为2(GroupId的两个不同数字)。


1
看看这个 Stack Overflow 的问题:https://dev59.com/Q2Ml5IYBdhLWcg3wP08a - Jeroen Heier
3个回答

16

以下是使用 Distinct 的一种方法:

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

或者您也可以使用GroupBy

ListOfMyClasses.GroupBy(t => t.GroupId).Count()

4

这应该对你有用。

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

首先,您正在选择所有 GroupId 。然后,您将它们过滤为不同的。最后,您获取这些值的计数。


0
此外,我想分享一些我在所有项目中使用的扩展,它也可以解决你的任务。
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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接