开发者

How can I reduce these four lines of code that splits/trims a semicolon list to one line?

开发者 https://www.devze.com 2022-12-16 07:08 出处:网络
How can I do this: string list 开发者_Go百科= \"one; two; three;four\"; List<string> values = new List<string>();

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消