c# - 获取 List<T> 中最常见的项目并在之后排序

标签 c# sql .net linq

我有一个 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());

关于c# - 获取 List<T> 中最常见的项目并在之后排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21434903/

相关文章:

c# - 带动态参数的动态 lambda 表达式

c# - SonarQube MSBuild runner 中的编程覆盖排除

c# - 为什么在 Contains 期间不调用 GetHashCode?

mysql - 如何在 MySQL 中读取 BINARY 列中的值

sql - WHERE 子句中的日期范围从 90 天前到今天的日期

.net - dotnet ef dbcontext 脚手架命令 --data-annotations 或 -d 命令行参数似乎不起作用

c# - 防止 C# Winform WebBrowser 中的 XSS

c# - 将项目添加到 EF Core 中的集合导航属性

sql - 计算每日变化和新销售人员

c# - 使类位于同一文件夹中的访问修饰符 "friends"