加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取List中最常见的项目,然后排序

发布时间:2020-12-16 00:10:29 所属栏目:百科 来源:网络整理
导读:我有一个List T已经填充了SQL数据库中的数据的对象/类的.我想要做的是找出这个表中最常见的用户是谁,并根据最常见的用户开始对新列表进行排序 我不知道如何在Stackoverflow上设置一个表格,所以你必须忍受我. 例如,数据库表可能如下所示: id - userID - rand
我有一个List< T>已经填充了SQL数据库中的数据的对象/类的.我想要做的是找出这个表中最常见的用户是谁,并根据最常见的用户开始对新列表进行排序

我不知道如何在Stackoverflow上设置一个表格,所以你必须忍受我.

例如,数据库表可能如下所示:

id - userID - randomColumn - randomColumn2
1 - 2 - ExampleText - ExampleText
2 - 2 - ExampleText - ExampleText
3 - 1 - ExampleText - ExampleText
4 - 3 - ExampleText - ExampleText
5 - 2 - ExampleText - ExampleText
6 - 1 - ExampleText - ExampleText

我想使用LINQ或SQL来格式化这个,所以我得到一个看起来像这样的列表

userID - amountColumn - randomColumn
2 - 3 - ExampleText
1 - 2 - ExampleText
3 - 1 - ExampleText

解决方法

使用LINQ提供的GroupBy扩展方法.

// Pseudo code
var grouped = list.GroupBy(item => item.UserID);

然后,您可以调用OrderByDescending对结果进行排序:

var sorted = grouped.OrderByDescending(group => group.Count());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读