【发布时间】:2021-03-13 05:33:51
【问题描述】:
我有一些看起来像:
{
"Item1": ["1a", "1b", "1c"],
"Item2": ["2a"],
"Item3": ["3a", "3b"]
}
我想要的是这个:
{
"1a": "Item1",
"1b": "Item1",
"1c": "Item1",
"2a": "Item2",
"3a": "Item3",
"3b": "Item3"
}
我已经能够做到这一点,但只是想知道是否有更简洁的 LINQ 方式?
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);
}
}
【问题讨论】:
-
更简洁并不一定意味着更好。
-
ToDictionary似乎没有必要。只需foreach超过items。 -
我会去 foreach。它更容易阅读。至少相同的性能。更容易调试。它实际上是 3 行代码。 foreach 中的变量名更清晰,从迭代到插入都一致。
标签: c# linq dictionary