简体   繁体   English

如何使用 LINQ 计算最大组中的对象数?

[英]How do I use LINQ to count number of objects in largest group?

How can I use LINQ to find the count of the largest group of objects in an object collection?如何使用 LINQ 查找对象集合中最大对象组的计数?

As an example:举个例子:

struct MyObject
{
    public int SomeInt;
    public int GroupInt;
}

List<MyObject> ObjectList = new List<MyOBject>();

// populate list

int LargestGroup = ObjectList.GroupBy(x => x.GroupInt).Max().Count();

This doesn't seem to work for me, as it resulted in an error:这似乎对我不起作用,因为它导致了错误:

ArgumentException: At least one object must implement IComparable. ArgumentException:至少一个对象必须实现 IComparable。

How can I correct this LINQ query (if it is wrong) or what should I look for to prevent this error if it is correct?我如何更正这个 LINQ 查询(如果它是错误的)或者如果它是正确的,我应该寻找什么来防止这个错误?

Your current query is trying to find the 'maximum group' and then subsequently retrieving that group's count.您当前的查询正在尝试查找“最大组”,然后检索该组的计数。 This clearly doesn't make sense;这显然没有意义; groups don't have any natural order, and there's no way for Enumerable.Max to know that you're interested in finding the group with the biggest Count .组没有任何自然顺序,并且Enumerable.Max无法知道您有兴趣找到具有最大Count的组。

What you probably want is:你可能想要的是:

int largestGroupCount = ObjectList.GroupBy(x => x.GroupInt)
                                  .Max(g => g.Count());

which uses the overload of Max that "Invokes a transform function on each element of a sequence and returns the maximum Int32 value."它使用Max的重载“对序列的每个元素调用变换函数并返回最大 Int32 值”。

One could view this as similar to:人们可以将其视为类似于:

int largestGroupCount = ObjectList.GroupBy(x => x.GroupInt)
                                  .Select(g => g.Count()) 
                                  .Max();

which creates a sequence by projecting each group to its count, and then finds the maximum of that sequence.其通过每一组投影到其计数创建一个序列,然后找到最大序列的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM