简体   繁体   English

如何转换字典 <object, string> 到字典 <object, List<string> &gt;使用LINQ

[英]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.

相关问题 如何获得字典 <string, List<Object> 与LINQ? - How to get a Dictionary<string, List<Object> with LINQ? 解析字典<string, List<KeyValuePair<string, string> &gt;&gt; 使用 LINQ 的对象 - Parse a Dictionary<string, List<KeyValuePair<string, string>>> object using LINQ Linq的“列表” <Dictionary<string, KeyValuePair<string, object> &gt;&gt;”按升序对值进行排序 - Linq for “List<Dictionary<string, KeyValuePair<string, object>>>” order the values by asc 从字典 <int,List<Tuple<string,object> &gt;&gt;到字典 <int,List<Tuple<string,object,AnEnum> &gt;&gt;与LINQ - From Dictionary<int,List<Tuple<string,object>>> to Dictionary<int,List<Tuple<string,object,AnEnum>>> with LINQ 转换列表 <object> 匿名类型到字典 <string, SortedList<DateTime, double> &gt; - Transform a List<object> of anonymous type to a Dictionary<string, SortedList<DateTime, double>> LINQ:转换字典 <int, Object> 列出 <List<string> &gt; - LINQ: Convert Dictionary<int, Object> to List<List<string>> 如何修改列表中的值 <Dictionary<string,object> &gt; - How to modify the value in List<Dictionary<string,object>> 如何转换字典 <string, object> 列出 <T> - How to convert Dictionary<string, object> to List<T> 如何转换列表<Claim>到字典<string,object> ? - How to convert List<Claim> to Dictionary<string,object>? 从列表中选择带有LINQ的行 <Dictionary<string, object> &gt; - Select rows with LINQ from List<Dictionary<string, object>>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM