简体   繁体   中英

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.

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.

How can I do the transform preferentially with 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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM