tags:

views:

389

answers:

8

Hi,

What is the easiest way to parse a comma delimited string list of values into some kind of object that I can loop through, so that I can access the individual values easily?

example string: "0, 10, 20, 30, 100, 200"

I'm a bit new to C#, so forgive me for asking a simple question like this. Thanks.

+2  A: 
   var stringToSplit = "0, 10, 20, 30, 100, 200";

    // To parse your string 
    var elements = test.Split(new[]
    { ',' }, System.StringSplitOptions.RemoveEmptyEntries);

    // To Loop through
    foreach (string items in elements)
    {
       // enjoy
    }
Asad Butt
+10  A: 

there are gotchas with this - but ultimately the simplest way will be to use

string s = [yourlongstring];
string[] values = s.Split(',');

If the number of commas and entries isn't important, and you want to get rid of 'empty' values then you can use

string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

One thing, though - this will keep any whitespace before and after your strings. You could use a bit of Linq magic to solve that:

string[] values = s.Split(',').Select(sValue => sValue.Trim()).ToArray();

That's if you're using .Net 3.5 and you have the using System.Linq declaration at the top of your source file.

Andras Zoltan
it should be noted that a regex solution is also available that would also cope with the whitespace either side. But this is the most direct approach.
Andras Zoltan
adding to @Andras's comment. I would use regular expression as well to also make sure each value is numeric and strip others out. Pattern? `"(?<value>\d+)"`, then you can get it in each `Match.Groups["value"]`. You could convert them to integers on the fly while doing so as well.
Robert Koritnik
+1  A: 

You can use this library: A Fast CSV Reader

Giorgi
is that available for Compact Framework for mobile apps?
Pentium10
+1  A: 

Use Linq, it is a very quick an easy way.

string mystring = "0, 10, 20, 30, 100, 200";

var query = from val in mystring.Split(',')
            select int.Parse(val);
foreach (int num in query)
{
     Console.WriteLine(num);
}
martin
try `int.Parse(val.Trim())`
Rob Fonseca-Ensor
Isn't it slightly overkill to use Linq for this. .split() returns an array which you could just loop though. You're adding the complexity of Linq, for no real benefit. If anything, it's reduced readability.
Simon P Stevens
but it's easy to understand what is happening and the compiler translates the query in the same way to an expression-tree as if you use lambda-querys
martin
linq isn't really that complex...
Rob Fonseca-Ensor
@Stevens, You could for-loop almost anything, really, and get the same results as Linq. I would personally prefer the `mystring.Split().Select()` syntax myself, as I'm more comfortable with it, but I don't think @martin's code is less readable because it uses "advanced" C# features.
strager
actually can't use Linq for my purposes since I'm running my code on .NET 2.0 but thanks.
ycomp
Yeah, true. It's largely down to personal preference I suppose. I use Linq a lot for processing data objects, this just feels a bit contrived to me. Everyone has their style though like you say.
Simon P Stevens
A: 

Look into the microsoft Jet engine ;) they have already handled most of the functionality you are likely to need, although this is an OTT solution if you are only handling a small amount of data, If so splitting the string on the delimiter as mentioned above ftw.

Microsoft JET Wiki

Yoda
A: 

You can use FileHelpers library to read CSV into an object. http://www.codeproject.com/KB/database/filehelpers.aspx

Hasan Khan
+2  A: 

The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.

string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");
Quick Joe Smith
A: 

I think it's better to use the Microsoft.VisualBasic.FileIO.TextFieldParser Class if you're working with comma separated values text files.

Islam Ibrahim