c# reversing and serializing a dictionary using linq -
was wondering possible reverse dictionary in single linq statement?
the structure follows;
dictionary<string, list<string>> original = new dictionary<string, list<string>>() { {"s", new list<string>() { "1", "2", "3" }}, {"m", new list<string>() { "4", "5", "6" }}, {"l", new list<string>() { "7", "8", "9" }}, {"xl", new list<string>() { "10", "11", "12" }}, };
which convert dictionary of type;
dictionary<string, string> reverse = new dictionary<string, string>() { {"1", "s"}, {"2", "s"}, //and on };
you can use selectmany
split value sublists, , reverse keys & values new dictionary using todictionary
var result = original .selectmany(k=> k.value.select(v => new { key = v, value = k.key } )) .todictionary( t=> t.key, t=> t.value);
Comments
Post a Comment