Search code examples
c#arrayslistpopulatejagged-arrays

How do you populate two Lists with one text file based on an attribute?


I have a text file with 40000 lines of data.

The data is formatted as such:

Anna,F,98273
Christopher,M,2736
Robert,M,827
Mary,F,7264
Anthony,M,8
...

I want to create two Lists based on a char value. The char indicates gender and I want to create a "female (f)" List and a "male (m)" List. How do I create two lists from one file based on this char value?

I have a class with a constructor already set up to create a List of all the data. I have already successfully created one List and am able to sort it based on any given attribute. If creating two Lists is not the best way to organize this data please give me alternatives.

I have thought about compiling all the data into one List and then sorting it based on the char so females are first and then males. I would then have to sort it based on the number associated with the name. The issue I run into here is I need to display the top 10 (any given int works here as it will be inputted by the user) female names with the highest numbers alongside the top male names with the highest numbers. I am not sure how to call on these values as I cannot (to my knowledge) use the index to indicate rank if both genders are in the same List. To me, this method seems much more complicated than simply creating two Lists and is not ideal.


Solution

  • By the suggestions in the comments, partialy @Charles_May 's:

    Simply looping:

    List<string> Source = {}; //source list
    List<string> Females = new List<string>(), Males = new List<string>(); 
    foreach (string value in Source)
    {
        if (value.ToUpper().Contains(",F,")) //Female
        {
            Females.Add(value);        
        }
        else
        {
            Males.Add(value);
        }
    }//result: both lists are with values
    

    That's it. if you's like to make it shorter:

    string filename = "textfilename.text" //file name to open
    List<string> Females = new List<string>(), Males = new List<string>(); 
    foreach (string line in File.ReadLines()) //openning file
    {
        if (line.ToUpper().Contains(",F,")) //Female
        {
            Females.Add(line);        
        }
        else
        {
            Males.Add(line);
        }
    }//same result
    

    to get other properties, maybe you'd like to use the method String.Split(',') which returnd array (in your case, string[3])