[c#] Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

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.

This question is related to c# string

The answer is


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.


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
}

   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
    }

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

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+");

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

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