How can I reduce these four lines of code that splits / truncates the semicolon list into one line?

How to do it:

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());
}

on one line, something like this:

List<string> values = extras.Split(';').ToList().ForEach( x => x.Trim()); //error
+3
source share
3 answers

You need to use Selectit if you want to perform the conversion for each instance in IEnumerable<T>.

List<string> values = list.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
+7
source

Ease of use of the LINQ selection method:

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

No explicit Trim(). Also not LINQ. Add \t, \r, \nin the char [], if there are other spaces.

-1
source

Source: https://habr.com/ru/post/1727791/


All Articles