C# Linq 问题 GROUP BY?
我有一个集合 List
,我试图找到一种方法来返回与出现次数最多的另一个字段相对应的字段。 我过去问过类似的问题,但我不确定如何将逻辑扩展到自定义类。 例如。
我的 CustomClass
具有三个公共属性:
Title
Mid
Eid
和一个 List
在循环中填充。
我需要执行 Linq 操作来返回出现最多相同 Eid
的类的 Mid
。因此,我们正在计算相同的 Eid
列。
我尝试过使用
var TopResult = MatchedFeatures.GroupBy(MatchedFeature => MatchedFeature).OrderByDescending(group => group.Count()).FirstOrDefault();
但它没有返回我正在寻找的内容。
谁能看到我哪里出错了?我正在使用 C#
这是之前提出的问题,它似乎工作得很好。现在在这种情况下如何扩展它......? C# 中的简单 LINQ 问题
非常感谢, 布雷特
I have a collection List<CustomClass>
which I am trying to find a way to return a field which corresponds to another field that occurs the highest number of times.
I've asked a similar question in the past, but I'm not sure how to extend the logic to a custom class.
For instance.
My CustomClass
has three public properties:
Title
Mid
Eid
And a List<CustomClass> MatchedFeatures = List<CustomClass>();
is populated in a loop.
I need to perform a Linq operation to return the Mid
of the class that has the largest number of occurring identical Eid
's. So we are counting the identical Eid
columns.
I have tried using
var TopResult = MatchedFeatures.GroupBy(MatchedFeature => MatchedFeature).OrderByDescending(group => group.Count()).FirstOrDefault();
But it doesn't return what I am looking for.
Can anyone see where I am going wrong? I am using C#
Here is the previous asked question, which seems to work fine. Now how to extend it in this case...?
Simple LINQ question in C#
Many thanks,
Brett
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要对
Eid
属性相同的要素进行分组,则应使用GroupBy(MatchedFeature => MatchedFeature.Eid)
。如果您省略
.Eid
,它只会将那些完全相同的功能分组在一起 - 而不是具有相同Eid
的功能。If you want to group those features where the
Eid
property is the same, you should useGroupBy(MatchedFeature => MatchedFeature.Eid)
.If you leave out the
.Eid
it will only group those features together which are entirely the same - not the ones that have the sameEid
.你必须做
MatchedFeature =>; MatchedFeature.Eid
而不是MatchedFeature => MatchedFeature
这是您的自定义类的一个实例,因此我相信您的自定义类的每个实例都会获得一个组。You have to do
MatchedFeature => MatchedFeature.Eid
instead ofMatchedFeature => MatchedFeature
which is an instance of your Custom class hense you get one group per instance of your custom class I believe.