Why Cant I do something like this?
If I have a List<String> myList
populated with items, I want to be able to act on each member in a conditional way like so:
myList.ForEach(a => { if (a.Trim().Length == 0) a = "0.0"; })
But this will not compile. Im guessing its something to do with missing a return value?
Im trying to prepare a list of strings for conversion to doubles, and I want the empty items to show '0.0' so I can just convert the whole list in one go.
ForEach is not mutable, it doesn't change the data structure in any way.
You can either:
Example of #1:
With .NET 3.5 and Linq:
With .NET 3.5, not using the Linq-syntax, but using the Linq-code:
Edit: If you want to produce a new list of doubles, you can also do that in one go using Linq:
Note that using "0.0" instead of just "0" relies on the decimal point being the full stop character. On my system it isn't, so I replaced it with just "0", but a more appropriate way would be to change the call to Double.Parse to take an explicit numeric formatting, like this:
@daniel-earwicker's
MutateEach
Extension solution is a good solution.Though, for returning a new
List
, you have the option to useList.ConvertAll<TTo>(Converter<TFrom,TTo>(Func<TFrom, TTo>))
, which has been around since .NET 2.0.It is not Linq, or Lambda.
MSDN Reference - List.ConvertAll
What you possibly want is:
Which would allow:
Just put the
MutateEach
method in a public static class of your own and make sure you have a using directive that will find it.Whether it's worth defining something like this depends on how often you'd use it. Note that it has to be an extension on
IList
instead ofIEnumerable
, so we can perform the updates, which makes it less widely applicable.