【问题标题】:How to get the count of the values that are repeated in c#如何获取在c#中重复的值的计数
【发布时间】:2013-06-02 09:25:46
【问题描述】:

我想找到使用 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。 希望你能理解我的问题。

【问题讨论】:

标签: c# linq lambda


【解决方案1】:
array.GroupBy(x => x)
     .Select(g => new {
                       Val = x.Key,
                       Cnt = x.Count()
                      }
            );

【讨论】:

    【解决方案2】:

    您可以在每个组上使用 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】:

      简单,使用 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 
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:
          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

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2023-03-24
              • 1970-01-01
              • 2022-11-08
              • 2012-12-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多