Reputation: 116
I have something that looks like:
{
"Item1": ["1a", "1b", "1c"],
"Item2": ["2a"],
"Item3": ["3a", "3b"]
}
What I want is this:
{
"1a": "Item1",
"1b": "Item1",
"1c": "Item1",
"2a": "Item2",
"3a": "Item3",
"3b": "Item3"
}
I've been able to do this, but just wondering if there is a more concise LINQ way?
Dictionary<string, string[]> items = new Dictionary<string, string[]>(...);
Dictionary<string, string> endResult = new Dictionary<string, string>(); // This is correct
var reversed = items.ToDictionary(x => x.Value, x => x.Key);
foreach (var item in reversed)
{
foreach (var inner in item.Key)
{
endResult.Add(inner, item.Value);
}
}
Upvotes: 0
Views: 205
Reputation: 42225
To add a slightly more concise way, taking advantage of the fact that Dictionary<TKey, TValue>
has a constructor which accepts an IEnumerable<KeyValuePair<TKey, TValue>>
:
Dictionary<string, string> result = new(
input.SelectMany(kvp => kvp.Value.Select(v => KeyValuePair.Create(v, kvp.Key))));
Upvotes: 1
Reputation: 24903
Dictionary<string, string> endResult = items.Select(o => o.Value.Select(v => new { Value = v, Key = o.Key }))
.SelectMany(o => o)
.ToDictionary(o => o.Value, o => o.Key);
Upvotes: 2