leora
leora

Reputation: 196489

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

Upvotes: 6

Views: 7552

Answers (3)

Arthur Ronald
Arthur Ronald

Reputation: 33785

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

Upvotes: 6

LukeH
LukeH

Reputation: 269368

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

Upvotes: 10

Andrew Cooper
Andrew Cooper

Reputation: 32576

var dict2 = dictionary.GroupBy(x => x.Key.Split('.')[0])
                      .ToDictionary(g => g.Key, g => g.First().Value);

Upvotes: 3

Related Questions