[英]what is the best way to convert one dictionary to another
i have one dictionary that has entries that looks like this:我有一本字典,其条目如下所示:
dictionary["ABC.123"] = "Test"
dictionary["DEF.123"] = "Test2"
dictionary["EFG.123"] = "Test3"
dictionary["EFG.343"] = "Test3"
dictionary["ABC.456"] = "Test"
and i want to create a new dictionary that looks like this: (basically parse out the beginning string before the "." and create that as the key and use the same value.我想创建一个看起来像这样的新字典:(基本上解析出“。”之前的开始字符串并将其创建为键并使用相同的值。
dictionary["ABC"] = "Test"
dictionary["DEF"] = "Test2"
dictionary["EFG"] = "Test3"
as you can see: there is always a 1 to 1 mapping between the first part of the key in the first dictionary to the value so there will be no clashes如您所见:第一个字典中键的第一部分与值之间始终存在一对一的映射,因此不会发生冲突
what is the easiest way using LINQ to convert to create the second dictionary from the first??使用 LINQ 转换从第一个字典创建第二个字典的最简单方法是什么?
I can loop through each record manually and parse out the new key and create each new record but i figured there was a LINQ way of doing it我可以手动遍历每条记录并解析出新密钥并创建每条新记录,但我认为有一种 LINQ 方法可以做到这一点
var newDict = dictionary.GroupBy(kvp => kvp.Key.Remove(kvp.Key.IndexOf('.')))
.ToDictionary(grp => grp.Key, grp => grp.First().Value);
Although a plain foreach
is probably going to be more readable and efficient:尽管普通的foreach
可能会更具可读性和效率:
var newDict = new Dictionary<string, string>();
foreach (var kvp in dictionary)
{
newDict[kvp.Key.Remove(kvp.Key.IndexOf('.'))] = kvp.Value;
}
A simple approach is to use the Select method to generate your desired KeyValuePair in conjuntion with ToDictionary一种简单的方法是使用 Select 方法与 ToDictionary 结合生成所需的 KeyValuePair
var response = dictionary
.Select(kvp => new KeyValuePair<string, string>(kvp.Key.Remove(kvp.Key.IndexOf('.')), kvp.Value))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var dict2 = dictionary.GroupBy(x => x.Key.Split('.')[0])
.ToDictionary(g => g.Key, g => g.First().Value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.