c# - List<int> 使用 linq 过滤

标签 c# .net linq

我有一个包含 Id 值的列表对象,例如它包含: 1,2,10,1,23,11,1,4,2,2,.. 等 我需要找出“1”,“2”,...等发生了多少次 在 C# 中使用 Linq

请帮忙。

最佳答案

使用 Enumerable.GroupBy 非常简单:

var grouped = list.GroupBy(x => x);

foreach (var group in grouped)
{
    Console.WriteLine("{0} appears {1} times", group.Key, group.Count());
}

或者:

var query = list.GroupBy(x => x, (x, g) => new { Key = x, Count = g.Count() }));

foreach (var result in query)
{
    Console.WriteLine("{0} appears {1} times", result.Key, result.Count);
}

(真正的区别在于我们何时将组转换为结果。)

关于c# - List<int> 使用 linq 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548005/

相关文章:

.net - 是否有等效于 Python 的 enumerate() for .NET IEnumerable

.net - 针对移动设备和桌面设备进行开发

c# - 使用 Linq 执行 List.Exist

c# - 调用线程一定是STA错误

c# - IEnumerable 问题 : Best performance?

c# - SelectSingleNode 返回 null - 即使有命名空间

c# - 可能有重复的键时如何添加到字典中?

c# - Linq 查询语法和扩展方法

c# - LINQ-to-SQL 中的多个 where 子句和 && 运算符有什么区别?

c# - Mindscape.Lightspeed 错误 : Invalid object name 'KeyTable'