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

前端 未结 5 1149
遇见更好的自我
遇见更好的自我 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:20

    Well, you could do this manually using a Dictionary:

    var frequencies = new Dictionary();
    foreach (var item in data)
    {
        int currentCount;
        // We don't care about the return value here, as if it's false that'll
        // leave currentCount as 0, which is what we want
        frequencies.TryGetValue(item, out currentCount);
        frequencies[item] = currentCount + 1;
    }
    

    A simpler but less efficient approach would be to use LINQ:

    var frequencies = data.ToLookup(x => x) // Or use GroupBy. Equivalent here...
                          .Select(x => new { Value = x.Key, Count = x.Count() })
                          .ToList();
    foreach (var frequency in frequencies)
    {
        Console.WriteLine("{0} - {1}", frequency.Value, frequency.Count);
    }
    

提交回复
热议问题