ForEach to Trim string values in string array
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 theForEach
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();
}
You need to assign the output of your ForEach to a new variable, like so:
var trimmedResult = m_days.Select(d => d.Trim()).ToList();
Because String.Trim()
do not modify original string. When you call ForEach(d => d.Trim())
you create new trimmed string in memory for each item of list, but that string is not assigned anywhere. Thats what you are doing:
foreach(string d in list)
{
d.Trim();
}
What you need is
m_days = days.Split(',').Select(d => d.Trim()).ToArray();