从列表中获取值

Use*_*ser 0 c# asp.net c#-3.0 c#-4.0

我创建列表就像

var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("1", "abc"));
list.Add(new KeyValuePair<string, string>("2", "def"));
list.Add(new KeyValuePair<string, string>("3", "ghi"));
Run Code Online (Sandbox Code Playgroud)

如何从此列表中选择值.这意味着我需要将1传递给列表并且需要取相等的值"abc".如何做到这一点?输入为1,输出为abc.

Jon*_*eet 6

听起来你只是想要:

var value = list.First(x => x.Key == input).Value;
Run Code Online (Sandbox Code Playgroud)

如果您确定钥匙将存在,那就是这样.否则,它有点棘手,部分原因KeyValuePair是因为它是一个结构.你可能想要:

var pair = list.FirstOrDefault(x => x.Key == input);
if (pair.Key != null)
{
    // Yes, we found it - use pair.Value
}
Run Code Online (Sandbox Code Playgroud)

你有什么理由不只是使用了Dictionary<string, string>吗?这是键/值对集合的更自然的表示:

var dictionary = new Dictionary<string, string>
{
    { "1", "abc" },
    { "2", "def" },
    { "3", "ghi" }
};
Run Code Online (Sandbox Code Playgroud)

然后:

var value = dictionary[input];
Run Code Online (Sandbox Code Playgroud)

再次,假设您知道密钥将存在.除此以外:

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
}
Run Code Online (Sandbox Code Playgroud)