如何转换List >到字典 >?

问题描述 投票:1回答:3

我有重复的键具有不同的值,我想将其转换为具有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 });
    }
}
c# linq
3个回答
5
投票
var list = tup.GroupBy(x => x.Item1)
              .ToDictionary(
                    x => x.Key, 
                    x => x.Select(y => y.Item2).ToList());

首先,我们按照GroupBy第1项进行分组。这应该足够明显了。

然后,我们称ToDictionary并传入keySelectorelementSelector。他们分别选择了密钥和值,给出了IGrouping<int, Tuple<int, int>>

供参考,this particular overload of ToDictionary is used

另外,正如Iridium在评论中所说,这也有效:

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

This overload of GroupBy allows you to select 2 things!


4
投票

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

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

3
投票

您可以使用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());

顺便说一下,在某些情况下你可以使用NameValueCollection,但这不是保存你的目标类型,例如

var nvc = tup.Aggregate(new NameValueCollection(),
  (seed, current) =>
  {
    seed.Add(current.Item1.ToString(), current.Item2.ToString());
    return seed;
  });

foreach (var item in nvc)
{
  Console.WriteLine($"Key = {item} Value = {nvc[item.ToString()]}");
}
© www.soinside.com 2019 - 2024. All rights reserved.