Reputation: 424
Was wondering is it possible to reverse a dictionary in a single LINQ statement?
The structure is as 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 i would like to convert to a dictionary of type;
Dictionary<string, string> Reverse = new Dictionary<string, string>()
{
{"1", "s"},
{"2", "s"}, //and so on
};
Upvotes: 2
Views: 374
Reputation: 101052
Something like:
var result = (from kvp in original
from value in kvp.Value
select new {Key = value, Value = kvp.Key}).ToDictionary(a => a.Key, a => a.Value);
Or, if you prefer the method syntax:
var result = original.SelectMany(kvp => kvp.Value.Select(v => new {Key = v, Value = kvp.Key}))
.ToDictionary(a => a.Key, a => a.Value);
Upvotes: 2
Reputation: 44268
you can use a SelectMany
to split the value sublists, and then reverse the Keys & Values into a 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);
Upvotes: 1
Reputation: 16636
For that you can use the SelectMany
LINQ extension method:
var 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" } },
};
var keyValuePairs = original.SelectMany(o => o.Value.Select(v => new KeyValuePair<string, string>(v, o.Key)));
Upvotes: 1
Reputation: 14318
If you do:
var reversed = original.SelectMany(x => x.Value.Select(y => new KeyValuePair<string, string>(y, x.Key)));
then you get:
1 - s
2 - s
3 - s
4 - m
5 - m
etc.
Upvotes: 2