我有一个类型字典,<string, string>对于特定情况,我需要进行反向查找.所以例如假设我有这个条目<"SomeString", "ab">并且我传入"ab"然后我想返回"SomeString".在我对foreach字典中的每个条目进行循环之前,我想知道进行此反向查找的最有效方法是什么?
Sel*_*enç 33
基本上,你可以使用LINQ并得到Key这样的,而不会反转任何东西:
var key = dictionary.FirstOrDefault(x => x.Value == "ab").Key;
Run Code Online (Sandbox Code Playgroud)
如果你真的想要反转你的词典,你可以使用这样的扩展方法:
public static Dictionary<TValue, TKey> Reverse<TKey, TValue>(this IDictionary<TKey, TValue> source)
{
var dictionary = new Dictionary<TValue, TKey>();
foreach (var entry in source)
{
if(!dictionary.ContainsKey(entry.Value))
dictionary.Add(entry.Value, entry.Key);
}
return dictionary;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
var reversedDictionary = dictionary.Reverse();
var key = reversedDictionary["ab"];
Run Code Online (Sandbox Code Playgroud)
注意:如果您有重复值,则此方法将添加第一个 Value并忽略其他值.
Ism*_*yel 28
使用Linq ToDictionary功能:
var reversed = d.ToDictionary(x => x.Value, x => x.Key);
Run Code Online (Sandbox Code Playgroud)
您可以在下面看到它的工作原理,在Linqpad中进行了测试:
var d = new Dictionary<int, string>();
d.Add(1,"one");
d.Add(2,"two");
d.Dump(); //prints it out in linq-pad
var reversed = d.ToDictionary(x => x.Value, x => x.Key);
reversed.Dump(); //prints it out in linq-pad
Run Code Online (Sandbox Code Playgroud)
如何使用 linq 函数 ToDictionary:
var reversedDictionary = dictionary.ToDictionary(x => x.Value, x => x.Key);
Run Code Online (Sandbox Code Playgroud)