How to count the frequency of bundle of number using c#?

前端 未结 5 1148
遇见更好的自我
遇见更好的自我 2020-12-12 06:21

Can somebody help me to run this program using c#. This program is to calculate the frequency of the number, for example 12 appear 10x. Before this I try to sort all list

5条回答
  •  既然无缘
    2020-12-12 07:00

    Assuming you have a list of numbers:

    var numbers = new List{ 1, 2, 3, 4, 1, 2, 2, 3 };
    

    Then we can use Linq to achieve what you want:

    var frequencies = 
        numbers.GroupBy( n => n ).Select( n => new { Value=n.Key, Count=n.Count() } );
    
    foreach (var f in frequencies)
    {
        Debug.WriteLine(string.Format("Value={0}, Frequency={1}", f.Value, f.Count));
    }
    

提交回复
热议问题