Home > other >  How to count the number of times a string appears in a column in a 2D array?
How to count the number of times a string appears in a column in a 2D array?

Time:10-09

I need to set up a 2D array to hold names of singers and their gender, and then count the number of males and display it into a label, and the number of females into another label. I've created the array (properly I think) but I do not know how to loop through only the 2nd column. Here's my array:

            string[,] singers =
        {
            {"Beyonce", "F"},
            {"David Bowie", "M"},
            {"Hikaru Utada", "F"},
            {"Madonna", "F"},
            {"Elton John", "M"},
            {"Koji Tamaki", "M"}
        };

I'm VERY new to C# so any assistance is appreciated.

CodePudding user response:

Instead of string[,] you can use string[][] and do something like

string[,] singers =
{
    {"Beyonce", "F"},
    {"David Bowie", "M"},
    {"Hikaru Utada", "F"},
    {"Madonna", "F"},
    {"Elton John", "M"},
    {"Koji Tamaki", "M"}
};


int females = 0, males = 0;
foreach(string[] arr in singers)
{
    if(arr[1] == "F") females  ;
    else if(arr[1] == "M") males  ;
}

In this method, you are essentially using an array of arrays to make iterating through it relatively easier. foreach loop gives each array in the two-dimensional array separately and you can check the element at index 1 to get the gender.

Or if you really have to use string[,], you can do

string[,] singers =
{
    {"Beyonce", "F"},
    {"David Bowie", "M"},
    {"Hikaru Utada", "F"},
    {"Madonna", "F"},
    {"Elton John", "M"},
    {"Koji Tamaki", "M"}
};

int females = 0, males = 0;
for (int i = 0; i < singers.GetLength(0); i  )
{
    if(singers[i, 1] == "F") females  ;
    else if(singers[i, 1] == "M") males  ;
}

array.GetLength(int dimension) gives the length of a particular dimension of an array. So we get the length of the first dimension, iterate through that and get the value at index 1 to access the gender values.

  •  Tags:  
  • c#
  • Related