[英]How to transform a Dictionary<object, string> to a Dictionary<object, List<string>> with LINQ
I have two methods that do the same thing, one works with a Dictionary<object, List<string>>
and another one with a Dictionary<object, string>
doing the same thing but iterating or not the list. 我有两个方法做同样的事情,一个用于
Dictionary<object, List<string>>
,另一个用Dictionary<object, string>
做同样的事情,但迭代或不迭代列表。
I want to reduce code duplication making just a method that works with Dictionary<object, List<string>>
and transforming the Dictionary<object, string>
to a Dictionary<object, List<string>>
with a list with only one string. 我想减少代码重复,只使用一个与
Dictionary<object, List<string>>
一起工作的方法,并将Dictionary<object, string>
转换为Dictionary<object, List<string>>
,其中包含只有一个字符串的列表。
How can I do the transform preferentially with LINQ? 如何使用LINQ优先进行转换?
Thanks in advance. 提前致谢。
Well you can't cast the dictionary that way, but you could use: 那么你不能用这种方式编译字典,但你可以使用:
var newDictionary = oldDictionary.ToDictionary(
pair => pair.Key,
pair => new List<string> { pair.Value });
var newDict = oldDict.ToDictionary(x => x.Key, x => new List<string> { x.Value });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.