Search code examples
c#genericscasting

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


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).


Solution

  • .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(); });