LINQ改造字典<关键字,值>到字典<价值,关键> [英] LINQ transform Dictionary<key,value> to Dictionary<value,key>
问题描述
我有一个低脑波一天......有谁知道一个快速和放大器;优雅的方式,使该密钥值,反之亦然改造字典?
例如:
VAR originalDictionary =新词典< INT,串> ()
{
{1,一},{2,二},{3,三}
};
变为
VAR newDictionary =新词典<字符串,整数>();
//内容:
// {
// {一,1},{二,2},{三公,3}
// }; // MSDN:
使用的 ToDictionary ?
orignalDictionary.ToDictionary(KP = GT; kp.Value,KP = GT; kp.Key);
这工作,因为的IDictionary< TKEY的,TElement>
;也是的IEnumerable< KeyValuePair< TKEY的,TElement>>
;.要知道,如果你有重复的值,你会得到一个异常。
如果您有重复的值,你需要什么就用他们做决定。一个简单的方法是,首先价值分组忽略重复,然后再进行解释。
originalDictionary
.ToLookup(KP = GT; kp.Value)
.ToDictionary(G => ; g.Key,G => g.First()键)。
I'm having a low-brainwave day... Does anyone know of a quick & elegant way to transform a Dictionary so that the key becomes the value and vice-versa?
Example:
var originalDictionary = new Dictionary<int, string>()
{
{1, "One"}, {2, "Two"}, {3, "Three"}
};
becomes
var newDictionary = new Dictionary<string, int>();
// contents:
// {
// {"One", 1}, {"Two", 2}, {"Three", 3}
// };
Use ToDictionary ?
orignalDictionary.ToDictionary(kp => kp.Value, kp => kp.Key);
This works because IDictionary<TKey,TElement>
; is also an IEnumerable<KeyValuePair<TKey,TElement>>
;. Just be aware that if you have duplicate values, you will get an exception.
In case you have duplicate values, you will need to decide on what to do with them. One simple way would be to ignore duplicates by grouping on Value first, then make the dictionary.
originalDictionary
.ToLookup(kp => kp.Value)
.ToDictionary(g => g.Key, g => g.First().Key);
这篇关于LINQ改造字典<关键字,值>到字典<价值,关键>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!