tags:

views:

68

answers:

2

I normally see the use of,foreach @ generics as

    List<int> lst = new List<int>();
    lst.Add(10);
    lst.Add(20);
    lst.Add(30);
    lst.ForEach(x => Console.WriteLine(x));

How can i achieve something similar:

lst.ForEach(x => x *x ) ?

A: 

Do you mean a map function? See this question http://stackoverflow.com/questions/702123/linq-map-or-collect

Nic Strong
+4  A: 
lst.Select(x => x * x ).ToList();

Hope that helps,

Dan

Daniel Elliott
Just to add to this, Dan's code returns an IEnumerable rather than another List: if you specifically need another List, then check out List<T>.ConvertAll. (Or call ToList() on Dan's expression of course.)
itowlson
Good point ... editted! :)
Daniel Elliott