I have a list like:
List<String> test = new List<String> {"Luke", "Leia"};
I would like to use something like this:
test.Select(s => String.Format("Hello {0}", s));
but it doesn't adjust the names in the list. Is there a way to use lambda expressions to alter these? Or is it because strings are immutable that this doesn't work?
Select doesn't modify the original collection; it creates a new IEnumerable<T> that you can enumerate with a foreach or convert to a list:
List<String> test2 = test.Select(s => String.Format("Hello {0}", s)).ToList();
test still contains "Luke" and "Leia", and test2 contains "Hello Luke" and "Hello Leia".
If you want to modify the original list with a lambda expression, you can apply the lambda expression to each list item individually and store the result back in the collection:
Func<string, string> f = s => String.Format("Hello {0}", s);
for (int i = 0; i < test.Count; i++)
{
test[i] = f(test[i]);
}
Here:
for(int i = 0; i < test.Count; i++) {
test[i] = String.Format("Hello {0}", test[i]);
}
No need to be fancy. No need to abuse LINQ. Just keep it simple.
You could go one step beyond this and create an extension method like so:
static class ListExtensions {
public static void AlterList<T>(this List<T> list, Func<T, T> selector) {
for(int index = 0; index < list.Count; index++) {
list[index] = selector(list[index]);
}
}
}
Usage:
test.AlterList(s => String.Format("Hello {0}", s));
Select
is for projecting and is really intended to be used in circumstances where there are no side-effects. Manipulating the items in the list very clearly has side-effects. In fact, the line
test.Select(s => String.Format("Hello {0}", s));
doesn't do anything except creating an IEnumerable<string>
that could eventually be enumerated over to produce the projection.
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