lov*_*iji 336 c# dictionary
如何在C#中按值获取Dictionary键?
Dictionary<string, string> types = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
getByValueKey(string value);
Run Code Online (Sandbox Code Playgroud)
getByValueKey("one")
必须回来"1"
.
这样做的最佳方式是什么?也许是HashTable,SortedLists?
Kim*_*imi 605
值不一定必须是唯一的,因此您必须进行查找.你可以这样做:
var myKey = types.FirstOrDefault(x => x.Value == "one").Key;
Run Code Online (Sandbox Code Playgroud)
如果值是唯一的并且插入频率低于读取值,则创建一个逆字典,其中值是键,键是值.
Zac*_*son 25
你可以这样做:
KeyValuePair<TKey, TValue>
字典中的所有内容(如果字典中有许多条目,这将是一个相当大的性能影响)如果不考虑性能,请使用方法1,如果不考虑内存,请使用方法2.
此外,所有键必须是唯一的,但这些值不必是唯一的.您可能有多个具有指定值的键.
你有什么理由不能扭转关键价值关系吗?
public static string GetKeyFromValue(string valueVar)
{
foreach (string keyVar in dictionaryVar.Keys)
{
if (dictionaryVar[keyVar] == valueVar)
{
return keyVar;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
其他人可能有更有效的答案,但我个人认为这更直观,并且适用于我的情况。
我遇到了 Linq 绑定不可用并且不得不显式扩展 lambda 的情况。它产生了一个简单的函数:
public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
T key = default;
foreach (KeyValuePair<T, W> pair in dict)
{
if (EqualityComparer<W>.Default.Equals(pair.Value, val))
{
key = pair.Key;
break;
}
}
return key;
}
Run Code Online (Sandbox Code Playgroud)
像这样调用它:
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string key = KeyByValue(dict, "two");
Console.WriteLine("Key: " + key);
}
Run Code Online (Sandbox Code Playgroud)
适用于 .NET 2.0 和其他受限环境。