将元组列表转换为字典

Rom*_*man 12 c#

何以最短的方式将元组列表转换为字典(C#)?

IList<Tuple<long, int>> applyOnTree = getTuples();
Run Code Online (Sandbox Code Playgroud)

Jon*_*n B 26

假设long是关键而且int是值;

applyOnTree.ToDictionary(x => x.Item1, x => x.Item2);
Run Code Online (Sandbox Code Playgroud)

显然,如果是相反的话,只需反转那两个.

  • 这是正确的,但只要记住在文件顶部包含“using System.Linq”指令即可。 (3认同)

tuk*_*aef 5

使用ToDictionary扩展方法:

var dictionary = applyOnTree.ToDictionary(l => l.Item1, l => l.Item2);
Run Code Online (Sandbox Code Playgroud)