Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading