如何转换List <tuple <int,int =“”>&gt; to Dictionary <int,list <int =“”>&gt;?

时间:2018-03-04 15:45:20

标签: c# linq

我有不同值的重复键,我想将其转换为包含1个键及其值的字典。

下一个例子将最好地解释我的意思:

var tup = new List<Tuple<int, int>>();
tup.Add(new Tuple<int, int>(1, 1));
tup.Add(new Tuple<int, int>(1, 2));

var dic = new Dictionary<int, List<int>>();

将tup转换为dic的优雅方法是什么?

我设法用foreach执行此操作,但希望在LINQ中编写它。

foreach (var item in tup)
{
    if (dic.ContainsKey(item.Item1))
    {
        dic[item.Item1].Add(item.Item2);
    }
    else
    {
        dic.Add(item.Item1, new List<int> { item.Item2 });
    }
}

3 个答案:

答案 0 :(得分:5)

import json
import xmltodict
with open("INSERT XML FILE LOCATION HERE", 'r') as f:
    xmlInString = f.read()
print("The xml file read-")
print(xmlInString)
JsonedXML = json.dumps(xmltodict.parse(xmlString), indent=4)
print("\nJSON format of read xml file-")
print(JsonedXML)
with open("myJson.json", 'w') as f:
    f.write(JsonedXML)

首先,我们按import json data = json.load(open('GIVE LOCATION OF THE CONVERTED JSON HERE')) token_key_value_dictionary=[] only_tokens_dictionary=[] uniqueKey ='xml' def recursive_json_parser(start_point_value,uniqueKey,start_point_key=''): if start_point_key !='': uniqueKey += '.'+start_point_key if type(start_point_value) is str or type(start_point_value) is unicode: token_key_value_dictionary.append([str(uniqueKey),str(start_point_value)]) only_tokens_dictionary.append(str(start_point_value)) uniqueKey ='' elif type(start_point_value) is list: for i in start_point_value: recursive_json_parser(i,uniqueKey) else: for key,value in start_point_value.items(): recursive_json_parser(value,uniqueKey,key) for key,value in data.items(): print (len(value)) recursive_json_parser(value,uniqueKey,key) f = open('tokens.txt','w') for row in only_tokens_dictionary: print (row) if row!='': f.write(row+'\n') f.close() 第1项进行分组。这应该足够明显了。

然后,我们致电var list = tup.GroupBy(x => x.Item1) .ToDictionary( x => x.Key, x => x.Select(y => y.Item2).ToList()); 并传递GroupByToDictionary。他们分别选择密钥和值,给定keySelector

供参考,this particular overload of ToDictionary is used

或者,正如Iridium在评论中所说,这也有效:

elementSelector

This overload of GroupBy allows you to select 2 things!

答案 1 :(得分:4)

首先需要按第一个元组元素进行分组,以便查找字典中具有相同键的所有元素。然后只需收集第二个元组元素并从中列出一个列表:

tup.GroupBy(t => t.Item1)
   .ToDictionary(g => g.Key, g => g.Select(t => t.Item2).ToList());

答案 2 :(得分:3)

您可以使用IGrouping<int, Tuple<int, int>>来解决此问题,例如:

var list = tup.GroupBy(x => x.Item1, x => x.Item2)
              .ToDictionary(x => x.Key, x => x.ToList());

BTW,在某些情况下,您可以使用GroupBy,但这不是保存您的目标类型,例如

var tup = new List<Tuple<int, int>>();
tup.Add(new Tuple<int, int>(1, 1));
tup.Add(new Tuple<int, int>(1, 2));

var dic = tup
         .GroupBy(x => x.Item1)
         .ToDictionary(x => x.Key, tuples => tuples.Select(x => x.Item2).ToList());