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.

2
  • 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. Feb 10, 2010 at 9: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, 2010 at 10:04

7 Answers 7

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.

3
  • 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. Feb 10, 2010 at 9: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? "(?<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. Feb 10, 2010 at 10:11
  • 1
    I adapted some of these to create List<long> userIds = usersList.Split(',').Select(sValue => long.Parse(sValue.Trim())).ToList();
    – Manish
    Jan 1, 2015 at 17:28
26
   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
    }
0
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);
}
5
  • 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. Feb 10, 2010 at 9: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, 2010 at 9: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, 2010 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, 2010 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. Feb 10, 2010 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+");
3

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

0
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;
}
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
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.