ForEach to Trim string values in string array

asp.net, c#, foreach

Solution

Because you are not reassigning the trimmed strings.

var list = m_days.Split(',').Select(s => s.Trim()).ToList();

Why `ForEach` doesn't work or if I am using the `ForEach` incorrectly?

`ForEach` is not Linq, it's a method of `List<T>`. What you are doing is basically this:

foreach(string day in m_days)
{
    day.Trim();  // you are throwing away the new string returned by String.Trim
}

Instead of using LINQ you could also use a `for`-loop instead:

for(int i = 0; i < m_days.Length; i++)
{
    m_days[i] = m_days[i].Trim();
}

Problem

I just wondered why this ForEach doesn't work and leaves the values with trailing whitespace. ``` string days = "Monday, Tuesday, Wednesday, Thursday, Friday"; string[] m_days = days.Split(','); m_days.ToList().ForEach(d => { d = d.Trim(); } ); ``` I know there are other ways of doing this so i don't need and answer there.

Original source