How to count occurences of an int in an array?

后端 未结 5 880
天命终不由人
天命终不由人 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条回答
  •  旧时难觅i
    2021-01-07 16:22

    Check out this Fiddle

    Or if you don't fancy clicking the link:

    var a = new int[]{2, 3, 4, 3, 4, 2, 4, 2, 4};
    var b = new int[a.Length];
    
        var aAsList = a.ToList();
    
        for (var i = 0;i < b.Length; i++)
        {
            var result = aAsList.Count(x=> x == i);
            b[i] = result;
    
            if (result != 0)
            {
                Console.WriteLine(string.Format("b[{0}] : {1}",i,result));
            }
        }       
    

提交回复
热议问题