142
votes

I want to split this line:

string line = "First Name ; string ; firstName";

into an array of their trimmed versions:

"First Name"
"string"
"firstName"

How can I do this all on one line? The following gives me an error "cannot convert type void":

List<string> parts = line.Split(';').ToList().ForEach(p => p.Trim()); 
8
The error is returned because ForEach works on current instance of IEnumerable and returns void.Majkel

8 Answers

341
votes

Try

List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();

FYI, the Foreach method takes an Action (takes T and returns void) for parameter, and your lambda return a string as string.Trim return a string

Foreach extension method is meant to modify the state of objects within the collection. As string are immutable, this would have no effect

Hope it helps ;o)

Cédric

26
votes

The ForEach method doesn't return anything, so you can't assign that to a variable.

Use the Select extension method instead:

List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
5
votes

Because p.Trim() returns a new string.

You need to use:

List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
4
votes

Here's an extension method...

    public static string[] SplitAndTrim(this string text, char separator)
    {
        if (string.IsNullOrWhiteSpace(text))
        {
            return null;
        }

        return text.Split(separator).Select(t => t.Trim()).ToArray();
    }
3
votes

Alternatively try this:

string[] parts = Regex.Split(line, "\\s*;\\s*");
2
votes

try using Regex :

List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList();
0
votes

Split returns string[] type. Write an extension method:

public static string[] SplitTrim(this string data, char arg)
{
    string[] ar = data.Split(arg);
    for (int i = 0; i < ar.Length; i++)
    {
        ar[i] = ar[i].Trim();
    }
    return ar;
}

I liked your solution so I decided to add to it and make it more usable.

public static string[] SplitAndTrim(this string data, char[] arg)
{
    return SplitAndTrim(data, arg, StringSplitOptions.None);
}

public static string[] SplitAndTrim(this string data, char[] arg, 
StringSplitOptions sso)
{
    string[] ar = data.Split(arg, sso);
    for (int i = 0; i < ar.Length; i++)
        ar[i] = ar[i].Trim();
    return ar;
}
-1
votes

Use Regex

string a="bob, jon,man; francis;luke; lee bob";
			String pattern = @"[,;\s]";
            String[] elements = Regex.Split(a, pattern).Where(item=>!String.IsNullOrEmpty(item)).Select(item=>item.Trim()).ToArray();;			
            foreach (string item in elements){
                Console.WriteLine(item.Trim());

Result:

bob

jon

man

francis

luke

lee

bob

Explain pattern [,;\s]: Match one occurrence of either the , ; or space character