How to count occurences of an int in an array?

后端 未结 5 877
天命终不由人
天命终不由人 2021-01-07 15:42

My array is A = {2, 3, 4, 3, 4, 2, 4, 2, 4}

I need an array B that stock at the index i the number of occurences of i in the a

5条回答
  •  独厮守ぢ
    2021-01-07 16:26

    If you want to find out how many time each item presents in the, say, array, you can use Linq:

      int[] a = new int[] 
       { 2, 3, 4, 3, 4, 2, 4, 2, 4 };
    
      // I'd rather not used array, as you suggested, but dictionary 
      Dictionary b = a
        .GroupBy(item => item)
        .ToDictionary(item => item.Key, item => item.Count());
    
     ...
    
    the outcome is
    
      b[2] == 3;
      b[3] == 2;
      b[4] == 4;
    

提交回复
热议问题