使用linq </int>列出<int>过滤

时间:2011-07-01 12:34:33

标签: c# .net linq

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

请帮助。

4 个答案:

答案 0 :(得分:13)

使用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);
}

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

答案 1 :(得分:12)

使用GroupBy

var les = new[] { 1, 2, 10, 1, 23, 11, 1, 4, 2, 2 };

var result = les
    .GroupBy(i => i, (e, g) => new { Value = e, Count = g.Count() });

或使用替代语法:

var result =
    from i in les
    group i by i
    into g
    select new { Value = g.Key, Count = g.Count() };

答案 2 :(得分:3)

 var l = new List<int> {1,2,10,1,23,11,1,4,2,2};
 l.GroupBy(i => i)
   .ToList()
   .ForEach(g => Console.WriteLine("{0} : {1}", g.Key, g.Count()));

答案 3 :(得分:2)

var list = new List<int> { 1, 2, 10, 1, 23, 11, 1, 4, 2, 2, };
var groups = list.GroupBy(i => i);
foreach (var group in groups)
    Console.WriteLine("{0} occurs {1} times", group.Key, group.Count());