user127815 user127815 - 1 year ago 65
C# Question

Putting contents of a .txt file into a List in

I have a .txt file that looks something like this:

1,Bob,Male //first row

2,Jim,Male //second row

3,Mary,Female //third row

I want to put these items into a generic list in c#, storing each column into something as "Id", "Name", "Gender" and treating each row as a different item of the list.

How would I go about doing this? I have no idea where to even start. I've looked at I/O operations and understand how to access a file, but I don't know how to create a variable name for each column and store each row as a new entry.

Answer Source
  1. Create Class which will represent your data. Lets call it Person Person will have 3 properties ID(int), Gender(string), Name(string)
  2. Create List<Person> listOfPerson = new List<Person>();
  3. Read the file line by line using loop -> Check File.ReadLines method
  4. Create new instance of the class in the loop Person person = new Person();
  5. Take the line from the file, call string.Split(',');
  6. Set person properties from the string[] which you create with splitting p.ID = arr[0] and so on
  7. Add the Person class to the List<Person>

I answer you with text so you should try something by yourself and learn how to do it in the future !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download