如何将Dictionary <object,string =“”>转换为Dictionary <object,list <string =“”>&gt;使用LINQ </object,> </object,>

时间:2012-01-02 14:27:15

标签: c# .net linq

我有两个方法做同样的事情,一个用Dictionary<object, List<string>>工作,另一个用Dictionary<object, string>做同样的事情但迭代或不用列表。

我想减少代码重复,只使用一个与Dictionary<object, List<string>>一起使用的方法,并使用只有一个字符串的列表将Dictionary<object, string>转换为Dictionary<object, List<string>>

如何使用LINQ优先进行转换?

提前致谢。

2 个答案:

答案 0 :(得分:13)

那么你不能投射字典,但你可以使用:

var newDictionary = oldDictionary.ToDictionary(
                                       pair => pair.Key,
                                       pair => new List<string> { pair.Value });

答案 1 :(得分:1)

var newDict = oldDict.ToDictionary(x => x.Key, x => new List<string> { x.Value });