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 ).
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(); }); Updated for 2010
List<int> l1 = new List<int>(new int[] { 1,2,3 } ); List<string> l2 = l1.ConvertAll<string>(x => x.ToString()); 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; -)
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.
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(); 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.
result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()
replace parameters and listOfInt with parameters