简体   繁体   中英

C# Split into multiple arrays

I have a situation where I need to split 1 csv file by splitting the commas and storing the columns in the array

here is part of the csv file:

Go,noowner,nocolour,0,0,0,0,-200,0,0,0,0,0,0,1301,985
Vine Street,bank,brown,60,30,50,50,4,20,60,180,320,450,0,1190,985
Community Chest,noowner,nocolour,0,0,0,0,0,0,0,0,0,0,0,1100,985
Coventry Street,bank,brown,60,30,50,50,2,10,30,90,160,250,0,1025,985
Income Tax,noowner,nocolour,0,0,0,0,200,0,0,0,0,0,0,935,985

Thanks in advance for the help Alex

So there's no header? Just select all lines and split them by comma:

string[][] allLinesFields = File.ReadLines(path)
    .Select(line => line.Split(','))
    .Where(array => array.Length == 16)
    .ToArray();

You can access all information via index, for example:

string nameOfFirstLine = allLinesFields[0][0];
string ownerOfFirstLine = allLinesFields[0][1];
string colorOfFirstLine = allLinesFields[0][2];
// and so on...

or use a loop to iterate all:

foreach(string[] fields in allLinesFields)
{
    string name = fields[0];
    string owner = fields[1];
    string color = fields[2];
}

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