将Tuple <list <guid>,string>转换为Dictionary <guid,list <string =“” >>

时间:2018-10-11 16:55:25

标签: c# list linq dictionary

我正在尝试将Tuple<List<Guid>, string>转换为Dictionary<Guid, List<string>>。这是我到目前为止的内容:

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));

1 个答案:

答案 0 :(得分: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) => new { key = y.Item2, value = z }上-您希望keyGuid,因此不是Item2,而应该是z,即Guid。因此,您可以采用我写的方式,也可以只是

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

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