Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression how to perform String.Format on List<String>?

Tags:

c#

lambda

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?

like image 612
Nyla Pareska Avatar asked Dec 30 '09 14:12

Nyla Pareska


2 Answers

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]);
}
like image 126
dtb Avatar answered Oct 12 '22 23:10

dtb


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.

like image 28
jason Avatar answered Oct 13 '22 00:10

jason