簡體   English   中英

C# 轉換列表<int>列出<double>

[英]C# Converting List<int> to List<double>

我有一個List<int>並且我想將它轉換為List<double> 除了像這樣循環遍歷List<int>並添加到新的List<double>之外,還有什么方法可以做到這一點:

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,所以答案可能會利用新的語言功能。

可以按照其他人的建議使用Select ,但您也可以使用ConvertAll

List<double> doubleList = intList.ConvertAll(x => (double)x);

這有兩個好處:

  • 它不需要 LINQ,所以如果您使用 .NET 2.0 並且不想使用LINQBridge ,您仍然可以使用它。
  • 它更有效: ToList方法不知道Select結果的大小,因此它可能需要在執行過程中重新分配緩沖區。 ConvertAll知道源和目標大小,因此它可以一次性完成所有操作。 它也可以在沒有迭代器抽象的情況下做到這一點。

缺點:

  • 它僅適用於List<T>和數組。 如果你得到一個普通的IEnumerable<T>你將不得不使用SelectToList
  • 如果您在項目中大量使用 LINQ,那么在這里繼續使用它可能會更加一致。

您可以使用 LINQ 方法:

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

或:

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

此外,列表類有一個 ForEach 方法:

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

您可以使用Select擴展方法執行此操作:

List<double> doubleList = intList.Select(x => (double)x).ToList();

您可以在 .Net Framework 2.0 中使用 ConvertAll 方法,這里是一個示例

        List<int> lstInt = new List<int>(new int[] { 1, 2, 3 });
        List<double> lstDouble = lstInt.ConvertAll<double>(delegate(int p)
        {
            return (double)p;
        });

您可以使用方法組:

lstDouble = lstInt.Select(Convert.ToDouble)

您可以使用 Select 或 ConvertAll。 請記住,ConvertAll 在 .Net 2.0 中也可用

.NET 3.5 - 4.8+

從.NET 3.5開始, LinQ Cast功能就是專門為此目的而創建的。

用法:

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

從上面鏈接的文檔中取出的示例:

System.Collections.ArrayList fruits = new System.Collections.ArrayList();
fruits.Add("mango");
fruits.Add("apple");
fruits.Add("lemon");

IEnumerable<string> query =
    fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);

// The following code, without the cast, doesn't compile.
//IEnumerable<string> query1 =
//    fruits.OrderBy(fruit => fruit).Select(fruit => fruit);

foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}

// This code produces the following output: 
//
// apple 
// lemon
// mango

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM