Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a List<T> from a comma separated string?

Tags:

c#

generics

Given the variable

string ids = Request.QueryString["ids"]; // "1,2,3,4,5";

Is there any way to convert it into a List without doing something like

List<int> myList = new List<int>();

foreach (string id in ids.Split(','))
{
    if (int.TryParse(id))
    {
        myList.Add(Convert.ToInt32(id));
    }
}
like image 496
Nick Allen Avatar asked May 26 '09 10:05

Nick Allen


People also ask

How do you convert a comma-separated string to a list in Python?

split() method to convert a comma-separated string to a list, e.g. my_list = my_str. split(',') . The str. split() method will split the string on each occurrence of a comma and will return a list containing the results.

How do you split a string to a list using a comma delimiter?

Use str. split() to convert a comma-separated string to a list. Call str. split(sep) with "," as sep to convert a comma-separated string into a list.

How can I convert comma-separated string into a list string C#?

To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.


2 Answers

To create the list from scratch, use LINQ:

ids.Split(',').Select(i => int.Parse(i)).ToList();

If you already have the list object, omit the ToList() call and use AddRange:

myList.AddRange(ids.Split(',').Select(i => int.Parse(i)));

If some entries in the string may not be integers, you can use TryParse:

int temp;
var myList = ids.Split(',')
    .Select(s => new { P = int.TryParse(s, out temp), I = temp })
    .Where(x => x.P)
    .Select(x => x.I)
    .ToList();

One final (slower) method that avoids temps/TryParse but skips invalid entries is to use Regex:

var myList = Regex.Matches(ids, "[0-9]+").Cast<Match>().SelectMany(m => m.Groups.Cast<Group>()).Select(g => int.Parse(g.Value));

However, this can throw if one of your entries overflows int (999999999999).

like image 163
Jason Avatar answered Sep 23 '22 01:09

Jason


This should do the trick:

myList.Split(',').Select(s => Convert.ToInt32(s)).ToList();

If the list may contain other data besides integers, a TryParse call should be included. See the accepted answer.

like image 37
Ronald Wildenberg Avatar answered Sep 22 '22 01:09

Ronald Wildenberg