C#转换列表< INT>列出<双>

C#转换列表< INT>列出<双>

问题描述:

我有一个列表&LT; INT&GT; ,我想将它转换为列表&LT;双&GT; 。有什么办法不是仅仅通过列表与LT循环做到这一点其他; INT&GT; ,并增加了新的列表&LT;双&GT; 像这样:

I have a List<int> and I want to convert it to a List<double>. Is there any way to do this other than just looping through the List<int> and adding to a new List<double> like so:

List<int> lstInt = new List<int>(new int[] {1,2,3});
List<double> lstDouble = new List<double>(lstInt.Count);//Either Count or Length, I don't remember

for (int i = 0; i < lstInt.Count; i++)
{
    lstDouble.Add(Convert.ToDouble(lstInt[0]));
}

有一个奇特的方式做到这一点?我使用C#4.0,所以答案可以利用的新的语言特性

Is there a fancy way to do this? I'm using C# 4.0, so the answer may take advantage of the new language features.

您可以使用LINQ的方法:

You can use LINQ methods:

List<double> doubles = integers.Select<int, double>(i => i).ToList();

List<double> doubles = integers.Select(i => (double)i).ToList();



此外,列表类有一个foreach方法:

Also, the list class has a ForEach method:

List<double> doubles = new List<double>(integers.Count);
integers.ForEach(i => doubles.Add(i));