Cast List<int> to List<string> in .NET 2.0

lomaxx picture lomaxx · Sep 5, 2008 · Viewed 81.5k times · Source

Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

Answer

Glenn Slaven picture Glenn Slaven · Sep 5, 2008

.NET 2.0 has the ConvertAll method where you can pass in a converter function:

List<int>    l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });