c# – How to display the number of elements in an array that have a specific value?


I created a string array, and randomly assigned values ​​to the elements using a variable of type int (0,1) and displayed "black" and "white" on the console. How to display also the number of elements in the array separately with the name "black" and the name "white"?

int numberOfBalls = 100;
string[] balls = new string[numberOfBalls];

Random rnd = new Random();
int a = rnd.Next(0, 2);

for (int i = 0; i < numberOfBalls; i++)
    a = rnd.Next(0, 2);
    if (a == 0)
        balls[i] = "beloe";
        balls[i] = "chernoe";

for (int i = 0; i < numberOfBalls; i++)


Or you can store 0 and 1 in the list (it takes up less space in memory), and check black / white before displaying the text.

Then the black sum will be var black = balls.Sum(); without any cycles (because there are only 0 and 1 in the list, then the sum of all elements will give us the sum of units, which is the number of "black" elements).

And the sum of whites: var white = numberOfBalls - black;

Scroll to Top