tags:

views:

120

answers:

2

I've got an array like this:

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

string store = parts[0];
string sku = parts[1];
string subcatcode = parts[2];
string price = parts[3];
string date = parts[4];
string desc = parts[5];

I want description to equal the joined value of all the parts with an index of 5 or higher. Will this work or is there a better way to do it?

string desc = string.Join(",", parts.Skip(5).ToArray());

The issue is that the last part of the CSV I'm parsing can contain commas (parts 0-4 are guaranteed not to).

A: 

Sure this should work just fine. If you want to get rid of the trailing comma's you can .TrimEnd() your string first.

Tim Jarvis
+7  A: 

Why not just specify a maximum count when you call Split?

string[] parts = line.Split(','.ToCharArray(), 6);

The last element (which you will assign to description) will include everything else, including the commas.

For data like "1,2,3,4,5,6,7,8" this will give you { "1", "2", "3", "4", "5", "6,7,8" }

Daniel LeCheminant
will this choke if a line has less than the specified count?
John Sheehan
Count is the maximum it will return, so no, it shouldn't choke. (Of course, if you say parts[5] you might get an exception thrown if there weren't enough parts)
Daniel LeCheminant
excellent, great answer. thanks
John Sheehan