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.
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With