使用LINQ计数列表中某项的出现次数 [英] Count Occurrences of an Item in a List using LINQ

查看:65
本文介绍了使用LINQ计数列表中某项的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to calculate the occurrences of an Item in a list using LINQ,

我有以下架构-

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

User (All Entries Provided), Count (To be Calculated)

计数应该是-

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

I cannot think of an elegant solution to this.

仅使用LINQ是否有可能?如果没有,我们如何使用带有一些C#代码的LINQ来实现这一目标.

Is it even possible only using LINQ? If not, how can we achieve this using LINQ with some C# Code.

推荐答案

您可以结合使用循环和

You can do that with a combination of loop and Enumerable.Take, Something like:

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; }
}

稍后您可以打印输出,如下所示:

Later you can print the output like:

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

这篇关于使用LINQ计数列表中某项的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆