我正在尝试使用 LINQ 计算列表中某项的出现次数,
我有以下架构-
用户(提供的所有条目),计数(待计算)
计数应该像 -
我想不出一个优雅的解决方案。
是否可以只使用 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/