views:

8421

answers:

7

Does anyone know if you can 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)

+6  A: 

Is C# 2.0 able to do List<T>.Convert? If so, I think your best guess would be to use that with a delegate:

List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });

Something along those lines.


Upvote Glenn's answer, which is probably the correct code ;-)

Erik van Brakel
A: 

You have to build a new list. The underlying bit representations of List<int> and List<string> are completely incompatible -- on a 64-bit platform, for instance, the individual members aren't even the same size.

It is theoretically possible to treat a List<string> as a List<object> -- this gets you into the exciting worlds of covariance and contravariance, and is not currently supported by C# or VB.NET.

Curt Hagenlocher
+1  A: 

You wouldn't be able to directly cast it as no explicit or implicit cast exists from int to string, it would have to be a method involving .ToString() such as:-

foreach (int i in intList) stringList.Add(i.ToString());

Edit - or as others have pointed out rather brilliantly, use intList.ConvertAll(delegate(int i) { return i.ToString(); });, however clearly you still have to use .ToString() and it's a conversion rather than a cast.

kronoz
The existence of a cast between the generic types has nothing to do with the ability to cast between the projection. IE, even if `int` were implicitly or explicitly convertible to `string`, that doesn't mean that `List<int>` has an implicit or explicit conversion to `List<string>`.
Adam Robinson
+42  A: 

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(); });
Glenn Slaven
awesome, thanks. after hours of painful searching I came here! and worked like a charm! :D
iamserious
A: 

@Curt:

It is theoretically possible to treat a List as a List -- this gets you into the exciting worlds of covariance and contravariance, and is not currently supported by C# or VB.NET

C# and .NET does actually support Covariance. Just not with generics.

Christian Hagelid
A: 

Thanks guys. ConvertAll FTW!

lomaxx
+6  A: 

Updated for 2010

List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<string>(x => x.ToString());
Luke
Thanks! This saved me a ton of time
Steve French