I have a List
and I want to convert it to a List
. Is there any way to do this other than just looping through the Li
You can use Select or ConvertAll. Keep in mind that ConvertAll is available in .Net 2.0 too
You can use ConvertAll method inside of .Net Framework 2.0 here is an example
List<int> lstInt = new List<int>(new int[] { 1, 2, 3 });
List<double> lstDouble = lstInt.ConvertAll<double>(delegate(int p)
{
return (double)p;
});
You can use Select
as suggested by others, but you can also use ConvertAll
:
List<double> doubleList = intList.ConvertAll(x => (double)x);
This has two advantages:
ToList
method doesn't know the size of the result of Select
, so it may need to reallocate buffers as it goes. ConvertAll
knows the source and destination size, so it can do it all in one go. It can also do so without the abstraction of iterators.The disadvantages:
List<T>
and arrays. If you get a plain IEnumerable<T>
you'll have to use Select
and ToList
.You can use a method group:
lstDouble = lstInt.Select(Convert.ToDouble)
You could do this using the Select extension method:
List<double> doubleList = intList.Select(x => (double)x).ToList();
You can use LINQ methods:
List<double> doubles = integers.Select<int, double>(i => i).ToList();
or:
List<double> doubles = integers.Select(i => (double)i).ToList();
Also, the list class has a ForEach method:
List<double> doubles = new List<double>(integers.Count);
integers.ForEach(i => doubles.Add(i));