如何获取c#中重复的值的计数

时间:2013-06-06 11:26:36

标签: c# linq lambda

我想找到使用linq查询重复的整数。例如,我的清单包括

var array = new int[]{1,1,1,2,2,2,2,3,3,9,9,16,16};

现在我想查询,我想将1计为3                                            将2计为4                                            将3计为2                                            将9计为2                                            将16计为2

我怎样才能在c#中使用linq。 希望你理解我的问题。

6 个答案:

答案 0 :(得分:13)

很简单,使用LINQ的GroupBy

var numbers = new int[] { 1, 1, 1, 2, 2, 2, 2, 3, 3, 9, 9, 16, 16 }; 

var counts = numbers
    .GroupBy(item => item)
    .Select(grp => new { Number = grp.Key, Count = grp.Count() });

结果:

Number    Count
1         3 
2         4 
3         2 
9         2 
16        2 

答案 1 :(得分:1)

array.GroupBy(x => x)
     .Select(g => new {
                       Val = x.Key,
                       Cnt = x.Count()
                      }
            );

答案 2 :(得分:1)

您可以在每个组中使用LINQ GroupBy然后Count

var dic = array.GroupBy(x => x)
               .ToDictionary(g => g.Key, g => g.Count());

在此处使用了ToDictionary,因此如果您有大量列表且需要经常访问,则可以更好地访问Dictionary获取Count

int count1 = dic[1]; //count of 1

答案 3 :(得分:1)

使用GroupBy + Count

var groups = array.GroupBy(i => i);

foreach(var group in groups)
    Console.WriteLine("Number: {0} Count:{1}", group.Key, group.Count());

请注意,您需要添加using System.Linq;

答案 4 :(得分:1)

使用Linq:

var NumArray= new int[] { 1, 1, 1, 2, 2, 2, 2, 3, 3, 9, 9, 16, 16 };
var counts = NumArray.GroupBy(item => item)
                     .Select(a=>new {Number=a.Key,Count =a.Count()});

答案 5 :(得分:0)

var array = new int[] {1,1,1,2,2,2,2,3,3,9,9,16,16}; 

var query = from x in array
            group x by x into g
            orderby count descending
            let count = g.Count()
            select new {Value = g.Key, Count = count};

foreach (var i in query)
{
    Console.WriteLine("Value: " + i.Value + " Count: " + i.Count);
}

结果将是;

Value: 1 Count: 3
Value: 2 Count: 4
Value: 3 Count: 2
Value: 9 Count: 2
Value: 16 Count: 2

这是DEMO