我正在学习 LINQ 我遇到了一个类似主题的问题。我不知道如何将 List 转换为 Dictionary
输入:列表编号 = 新列表{2,3,4,5}
输出:2->4、3->9 等...
答案 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