【问题标题】:Converting Tuple<List<Guid>, string> to Dictionary<Guid, List<string>>将 Tuple<List<Guid>, string> 转换为 Dictionary<Guid, List<string>>
【发布时间】:2018-10-11 16:55:24
【问题描述】:

我正在尝试将Tuple&lt;List&lt;Guid&gt;, string&gt; 转换为Dictionary&lt;Guid, List&lt;string&gt;&gt;。这是我到目前为止所拥有的:

var listOfTuples = GetListOfTuples(); // returns type List<Tuple<List<Guid>, string>>
var transformedDictionary = new Dictionary<Guid, List<string>>();
foreach (var listOfTuple in listOfTuples)
{
    foreach (var key in listOfTuple.Item1)
    {
        if (!transformedDictionary.ContainsKey(key)) 
            transformedDictionary[key] = new List<string> { listOfTuple.Item2 };
        else transformedDictionary[key].Add(listOfTuple.Item2);
    }
}

有没有更好的方法,也许是使用 LINQ; SelectManyGroupingtoDictionary?

更新:我试过了,但显然不行:

listOfTuples.ToList()
 .SelectMany(x => x.Item1,(y, z) => new { key = y.Item2, value = z })
 .GroupBy(p => p.key)
 .ToDictionary(x => x.Key, x => x.Select(m => m.key));

【问题讨论】:

  • 您尝试过任何 linq 解决方案吗?
  • 我有。但我无法让它工作。
  • 请分享您的尝试
  • 如果您将逻辑拆分为 LINQ 的步骤,这非常容易。首先,您可以使用 SelectMany 将原始列表转换为 1 对 1,然后从那里您需要的是正确的 GroupBy,您应该能够通过这些提示弄清楚如何做到这一点。
  • 这似乎是一个 X,Y 问题,为什么你首先要有那个数据结构

标签: c# list linq dictionary


【解决方案1】:

你很接近。问题在于选择正确的键和值

var result = listOfTuples.SelectMany(t => t.Item1.Select(g => (g, str: t.Item2)))
                         .GroupBy(item => item.g, item => item.str)
                         .ToDictionary(g => g.Key, g => g.ToList());

这里的错误是(y, z) =&gt; new { key = y.Item2, value = z } - 您希望key 成为Guid,因此它应该是z 而不是Item2,它应该是z,即Guid。所以你可以按照我写的方式去,或者只是

(y, z) => new { key = z, value = y.Item2 }

也不需要开头的.ToList()。你说listOfTuples 已经返回了一个列表

【讨论】:

  • 谢谢你,@gilad-green。我将首先尝试您对我的代码的更正。我也会分析你的方法,这对我来说是新的。我还注意到,在我的 LINQ 代码 sn-p 中,最后一部分需要更新为 .ToDictionary(x =&gt; x.Key, x =&gt; x.Select(m =&gt; m.value))
  • @Tom - 如果有帮助,请告诉我 :) 很高兴您发布了您尝试过的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多