Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
lomaxx Avatar asked Sep 04 '08 23:09

lomaxx


People also ask

Can you add a list to a list C #?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2); Let us see the complete code.

Can you cast an int to a string C#?

Converting int to string in C# is used to convert non-decimal numbers to string character. This can be done by using int to string conversion, int to string with Int32. ToString(), int to string with string concatenation, int to string with StringBuilder, int to string with Convert.


2 Answers

.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(); }); 
like image 110
Glenn Slaven Avatar answered Sep 28 '22 03:09

Glenn Slaven


Updated for 2010

List<int> l1 = new List<int>(new int[] { 1,2,3 } ); List<string> l2 = l1.ConvertAll<string>(x => x.ToString()); 
like image 28
Luke Avatar answered Sep 28 '22 04:09

Luke