Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of Tuples to Dictionary

Tags:

c#

How to convert in the shortest way a list of Tuples to Dictionary (C#) ?

IList<Tuple<long, int>> applyOnTree = getTuples();
like image 749
Roman Avatar asked Nov 01 '12 15:11

Roman


People also ask

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can we use list of tuple as key in dictionary?

A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.


2 Answers

Assuming the long is the key and the int is the value;

applyOnTree.ToDictionary(x => x.Item1, x => x.Item2);

Obviously, just reverse those two if it's the other way around.

like image 172
Jon B Avatar answered Sep 17 '22 15:09

Jon B


Use ToDictionary extension method:

var dictionary = applyOnTree.ToDictionary(l => l.Item1, l => l.Item2);
like image 35
tukaef Avatar answered Sep 21 '22 15:09

tukaef