63

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
ycomp
  • 8,316
  • 19
  • 57
  • 95
  • re: my answer - if you're actually treating these as numbers as well then there are additional strategies for parsing them out in a fault-tolerant manner if you're interested. I did start adding them on - but felt it was actually too much information. – Andras Zoltan Feb 10 '10 at 09:59
  • actually yes I did need them as #s but I implemented it just now, it was easy after following your code. Everything working fine. thanks! – ycomp Feb 10 '10 at 10:04

7 Answers7

153

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
  • 41,961
  • 13
  • 104
  • 160
  • 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 Feb 10 '10 at 09:40
  • 1
    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? `"(?\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 Feb 10 '10 at 10:11
  • 1
    I adapted some of these to create List userIds = usersList.Split(',').Select(sValue => long.Parse(sValue.Trim())).ToList(); – Manish Jan 01 '15 at 17:28
25
   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
  • 21,468
  • 17
  • 69
  • 94
8

Use Linq, it is a very quick and 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
  • 2,957
  • 3
  • 25
  • 46
  • 4
    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 Feb 10 '10 at 09:44
  • 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 Feb 10 '10 at 09:51
  • 3
    @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 Feb 10 '10 at 10:03
  • actually can't use Linq for my purposes since I'm running my code on .NET 2.0 but thanks. – ycomp Feb 10 '10 at 10:06
  • 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 Feb 10 '10 at 11:01
4

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
  • 8,074
  • 3
  • 29
  • 33
3

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

Islam Yahiatene
  • 1,441
  • 14
  • 27
2

Sometimes the columns will have commas within themselves, such as:

"Some item", "Another Item", "Also, One more item"

In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):

private IList<string> GetColumns(string columns)
{
    IList<string> list = new List<string>();

    if (!string.IsNullOrWhiteSpace(columns))
    {
        if (columns[0] != '\"')
        {
            // treat as just one item
            list.Add(columns);
        }
        else
        {
            bool gettingItemName = true;
            bool justChanged = false;
            string itemName = string.Empty;

            for (int index = 1; index < columns.Length; index++)
            {
                justChanged = false;
                if (subIndustries[index] == '\"')
                {
                    gettingItemName = !gettingItemName;
                    justChanged = true;
                }

                if ((gettingItemName == false) &&
                (justChanged == true))
                {
                    list.Add(itemName);
                    itemName = string.Empty;
                    justChanged = false;
                }

                if ((gettingItemName == true) && (justChanged == false))
                {
                    itemName += columns[index];
                }
            }
        }
    }

    return list;
}
James John McGuire 'Jahmic'
  • 11,728
  • 11
  • 67
  • 78
1

Use a loop on the split values

string values = "0,1,2,3,4,5,6,7,8,9";

foreach(string value in values.split(','))
{
    //do something with individual value
}
jelde015
  • 554
  • 6
  • 7