I am wanting to trim any white space off a collection of strings. I used the following code but it doesn't seem to work. Could anyone explain why?
result.ForEach(f => f = f.Trim());
This finally brings us to the answer to our question, why can't we break out of a forEach() loop? It's because the loop is running that callback function over every item, so even if you write a return it's only returning on that instance of the function.
Exit Foreach Loop Using break Keyword In C# Let's say you have a list of colors or an array of colors and you are looping through the list and now you have to exit the foreach loop, you will use the break keyword to exit the loop.
The foreach command implements a loop where the loop variable(s) take on values from one or more lists. In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to assign to varname. The body argument is a Tcl script.
For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time.
This won't work because you are assigning a new string reference to a local variable. This is probably what you are looking for:
result = result.Select(f => f.Trim()).ToList();
You are re-assigning the argument variable inside the scope of the lambda. It's a collapsed form of:
foreach(string value in myList)
{
Lambda(value);
}
void Lambda(string input)
{
input = input.Trim();
}
The simplest way would probably be to use a projection:
myList = myList.Select(str => str.Trim()).ToList();
foreach
doesn't give you write access to the underlying collection, it only iterates through it, which means your change isn't stored back into the collection.
You can do two things:
Produce a new collection
var newResult = result.Select(f => f.Trim()).ToList();
Use a normal for-loop and change the original collection
for (int index = 0; index < result.Count; index++)
result[index] = result[index].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