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

C#String

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

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

Solution 7 - C#

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionycompView Question on Stackoverflow
Solution 1 - C#Andras ZoltanView Answer on Stackoverflow
Solution 2 - C#AsadView Answer on Stackoverflow
Solution 3 - C#martinView Answer on Stackoverflow
Solution 4 - C#Quick Joe SmithView Answer on Stackoverflow
Solution 5 - C#Islam YahiateneView Answer on Stackoverflow
Solution 6 - C#JahmicView Answer on Stackoverflow
Solution 7 - C#jelde015View Answer on Stackoverflow