简体   繁体   中英

Comma Separated text file to Generic List

Having a bit of trouble with converting a comma separated text file to a generic list. I have a class (called "Customers") defined with the following attributes:

  • Name (string)
  • City (string)
  • Balance (double)
  • CardNumber (int)

The values will be stored in a text file in this format: Name,City, Balance, CarNumber eg John,Memphis,10,200789. There will be multiple lines of this. What I want to do is have each line be placed in a list item when the user clicks a button.

I've worked out I can break each line up using the .Split() method, but have no idea how to make the correct value go into the correct attribute of the list. (Please note: I know how to use get/set properties, and I am not allowed to use LINQ to solve the problem).

Any help appreciated, as I am only learning and have been working on this for a for while with no luck. Thanks

EDIT:
Sorry, it appears I'm not making myself clear. I know how to use .add. If I have two lines in the text file: A,B,1,2 and C,D,3,4 What I don't know how to do is make the name "field" in the list item in position 0 equal "A", and the name "field" in the item in position 1 equal "C" and so on.

Sorry for the poor use of terminology, I'm only learning. Hope you understand what I'm asking (I'm sure it's really easy to do once you know)

The result of string.Split will give you an array of strings:

string[] lineValues = line.Split(',');

You can access values in an array by index:

string name = lineValues[0];
string city = lineValues[1];

You can convert strings to double or int using their respective Parse methods:

double balance = double.Parse(lineValues[2]);
int cardNumber = int.Parse(lineValues[3]);

You can instantiate the class and assign to it very simply:

Customer customerForCurrentLine = new Customer()
{
    Name = name,
    City = city,
    Balance = balance,
    CardNumber = cardNumber,
};

Simply loop over the lines, instantiate a Customer for that line, and add it to a variable you've created of the type List<Customer>

If you want your program to be bulletproof, you're going to have to do a lot of checking to skip over lines that don't have enough values, or that would fail to parse to the correct number type. For example, check lineValues.Length == 4 and use int.TryParse(...) and double.TryParse(...) .

Read a file and split its text based on newline character. Then for total line count run a loop that will split based on comma and create a new object and insert values in its properties and add that object to a list.

This way

List<Customers> lst = new List<Customers>();

string[] str = System.IO.File.ReadAllText(@"C:\CutomersFile.txt")
                             .Split(new string[] { Environment.NewLine }, 
                                                   StringSplitOptions.None);

for (int i = 0; i < str.Length; i++)
{
    string[] s = str[i].Split(',');

    Customers c = new Customers();

    c.Name = s[0];
    c.City = s[1];
    c.Balance = Convert.ToDouble(s[2]);
    c.CardNumber = Convert.ToInt32(s[3]);

    lst.Add(c);
}

BTW class name should be Customer and not Customers

Split() generates an array of strings in the order they appeared in the source string. Thus, if your name field is the first column in the CSV file, it will always be the first index in the array.

someCustomer.Name = splitResult[0];

And so on. You'll also need to investigate String.TryParse for your class's numerically typed properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM