tags:

views:

155

answers:

3

How can I do this:

string list = "one; two; three;four";

List<string> values = new List<string>();
string[] tempValues = list.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
foreach (string tempValue in tempValues)
{
    values.Add(tempValue.Trim());
}

in one line, something like this:

List<string> values = extras.Split(';').ToList().ForEach( x => x.Trim()); //error
+7  A: 

You need to use Select if you want to perform a transformation on each instance in the IEnumerable<T>.

List<string> values = list.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
Adam Robinson
Forgot a `.ToList()`
Tinister
You need a ToList() at the end, since Select returns an `IEnumerable<T>`, not a `List<T>`
Thomas Levesque
@Tinister, Thomas: Thanks, I realized that shortly after I posted the answer. I've since updated it.
Adam Robinson
+3  A: 

Easy -- use the LINQ select method:

var values = "one; two; three;four".Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim());
David Pfeffer
A: 
List<string> values = new List<string>(list.Split(new char[] { ';', ' ' }, StringSplitOptions.RemoveEmptyEntries));

No explicit Trim() is necessary. Nor is LINQ. Add \t, \r, \n to the char[] if other whitespace may be present.

JMD
Interesting idea, but fails for cases like `"twenty;twenty one;twenty two"`. Spaces are often present in semicolon delimited lists.
280Z28
Fair enough! Although, pedantically-speaking, he did ask about a very specific string. ;)
JMD
@JMD: If you really want to go there, then an easier solution would be `new List<string>() {"one", "two", "three", "four"};`
Adam Robinson