听起来你只是想要:
var value = list.First(x => x.Key == input).Value;
那是如果你确定钥匙会出现。否则它会有点棘手,部分原因KeyValuePair
是它是一个结构。你可能想要:
var pair = list.FirstOrDefault(x => x.Key == input);
if (pair.Key != null)
{
// Yes, we found it - use pair.Value
}
你有什么理由不只是使用aDictionary<string, string>
吗?这是键/值对集合更自然的表示:
var dictionary = new Dictionary<string, string>
{
{ "1", "abc" },
{ "2", "def" },
{ "3", "ghi" }
};
然后:
var value = dictionary[input];
同样,假设您知道密钥将存在。否则:
string value;
if (dictionary.TryGetValue(input, out value))
{
// Key was present, the value is now stored in the value variable
}
else
{
// Key was not present
}