How can I do this:
string list 开发者_Go百科= "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
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();
Easy -- use the LINQ select method:
var values = "one; two; three;four".Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim());
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.
精彩评论