Reputation: 3459
I am trying to split a string into a list of values, by splitting it by a given character. I need it to be a list rather than an array because the number of values can change. How would I go about doing this?
For example:
String s = "red, green, blue, unicorn";
would become a list where the element at index 0 is red, then 1 is green, etc.
Upvotes: 1
Views: 1015
Reputation: 2167
I have to split a string into a list because i dont know how many values the list is going to have.
I am not sure why you think you need a list to know how many values are returned by Split?
The call to Split does tell you how many values it finds.
For Example:
using System;
namespace SampleApplication
{
static class Program
{
[STAThread]
static void Main()
{
var input = "one,two,three,four,five,six";
string [] words = input.Split(',');
Console.WriteLine("Number of Words: {0}", words.Length);
foreach (object value in words)
{
Console.WriteLine(value.ToString());
}
}
}
}
This code produces this output:
C:\temp>test
Number of Words: 6
one
two
three
four
five
six
C:\temp>
Upvotes: 0
Reputation: 116401
String.Split[]
returns string[]
. The array will hold however many elements the string had. Can't you use that? See http://msdn.microsoft.com/en-us/library/b873y76a.aspx
Upvotes: 2
Reputation: 120390
Assuming your string is comma delimited:
var str = "this, is, a, list, of, stuff";
var list =
str
.Split(',')
//.Select(s => s.Trim()) //maybe a good idea?
.ToList();
Upvotes: 4