Cast list <int> for displaying <string> in .NET 2.0

Can you somehow defer List<int> to List<string> ?

I know that I could iterate over the .ToString () thing too, but the cast would be awesome.

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

+94
generics casting c #
Sep 04 '08 at 23:06
source share
7 answers

In .NET 2.0 there is a ConvertAll method in which you can pass 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(); }); 
+151
Sep 04 '08 at 23:16
source share

Updated for 2010

 List<int> l1 = new List<int>(new int[] { 1,2,3 } ); List<string> l2 = l1.ConvertAll<string>(x => x.ToString()); 
+113
Mar 02
source share

Is it possible to execute List<T>.Convert with C # 2.0? If so, I think your best guess would be to use this 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 like that.




The answer is Upnote Glenn, which is probably the right code; -)

+8
Sep 04 '08 at 23:11
source share

You cannot directly use it, since explicit or implicit listing exists from int to string, it must be a method that includes .ToString (), for example: -

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

Change - or, as others have noted rather brilliantly, use intList.ConvertAll (delegate (int i) {return i.ToString ();}); however, nevertheless, you still have to use .ToString () and this conversion, not casting.

+5
Sep 04 '08 at 23:14
source share

You can use:

 List<int> items = new List<int>(new int[] { 1,2,3 } ); List<string> s = (from i in items select i.ToString()).ToList(); 
+5
Mar 02 '13 at 18:33
source share

You need to create a new list. The basic representations of the List<int> and List<string> bits are completely incompatible - on a 64-bit platform, for example, individual members do not have the same size.

Theoretically, you can consider a List<string> as a List<object> - this leads you to the exciting worlds of covariance and contravariance and is currently not supported by C # or VB.NET.

+1
Sep 04 '08 at 23:12
source share

result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()

replace parameters and listOfInt with parameters

+1
Jun 07 '17 at 10:03
source share



All Articles