简体   繁体   中英

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??

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

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:

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

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);

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