How to count occurences of an int in an array?

后端 未结 5 1112
执念已碎
执念已碎 2021-01-07 15:57

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:13

    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));
            }
        }       
    

提交回复
热议问题