如何从 List<double> 制作 Dictionary<double, double>

时间:2021-04-15 08:58:47

标签: c# .net linq

我正在学习 LINQ 我遇到了一个类似主题的问题。我不知道如何将 List 转换为 Dictionary,其中 Key 是 list 中的 double,Value 是这个数字的平方。我知道像 .ToDictionary() 这样的方法,但不知道如何在我的情况下使用它。

输入:列表编号 = 新列表{2,3,4,5}

输出:2->4、3->9 等...

2 个答案:

答案 0 :(得分:0)

var squared = numbers.ToDictionary(x => x, x => x * x);

然而,IMO 这是非常不必要的。执行乘法可能比字典查找便宜。

答案 1 :(得分:0)

在需要时进行乘法可能会更好。

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var dataSet = new List<double>()
        {
            2,3,4,5
        };
        
        var result = dataSet.ToDictionary(k => k, v => v * v);
        foreach(var kv in result)
        {
            Console.WriteLine("{0} = {1}",kv.Key, kv.Value);
        }
    }
}

输出:

2 = 4
3 = 9
4 = 16
5 = 25
相关问题