c# - 使用 LINQ 计算列表中项目的出现次数

标签 c# linq linq-to-sql

我正在尝试使用 LINQ 计算列表中某项的出现次数,

我有以下架构-

用户(提供的所有条目),计数(待计算)

计数应该像 -

enter image description here

我想不出一个优雅的解决方案。

是否可以只使用 LINQ?如果没有,我们如何使用带有一些 C# 代码的 LINQ 来实现这一点。

最佳答案

您可以结合使用循环和 Enumerable.Take 来做到这一点, 像这样的东西:

for (int i = 0; i < list.Count; i++)
{
    //Get count of current element to before:
    int count = list.Take(i+1)
                    .Count(r => r.UserName == list[i].UserName);
    list[i].Count = count;
}

您的 list 定义为:

List<User> list = new List<User>
    {
        new User{UserName = "A"},
        new User{UserName = "B"},
        new User{UserName = "A"},
        new User{UserName = "A"},
        new User{UserName = "B"},
        new User{UserName = "A"},
        new User{UserName = "C"},
        new User{UserName = "A"},

    };

User 类为:

public class User
{
    public string UserName { get; set; }
    public int Count { get; set; }
}

稍后您可以像这样打印输出:

foreach (var item in list)
{
    Console.WriteLine("UserName: {0}, Running Total: {1}", item.UserName, item.Count);
}

你会得到:

UserName: A, Running Total: 1
UserName: B, Running Total: 1
UserName: A, Running Total: 2
UserName: A, Running Total: 3
UserName: B, Running Total: 2
UserName: A, Running Total: 4
UserName: C, Running Total: 1
UserName: A, Running Total: 5

关于c# - 使用 LINQ 计算列表中项目的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21733278/

相关文章:

c# - foreach 循环内更快的数据检查和更新

c# - Linq to SQL 的问题

c# - 在特定时间启动和停止视频 Windows Media Player

c# - Crystal Reports 搞乱富文本

C# Linq : Can you merge DataContexts?

c# - 使用通用列表作为数据源和自动生成列的 Gridview

c# - 如何更改 DataContext 中的数据库名称

sql-server - 在具有复合主键的表上使用 linq-to-sql 时出现错误

c# - 如何在代码隐藏中设置DB ConnectionStringSettings

c# - WPF 中命令绑定(bind)的默认参数是什么?