繁体   English   中英

从列表中获取值

[英]Get the value from list

我创建列表像

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"));

如何从此列表中选择值。 这意味着我需要将1传递给列表,并且需要使用相等的值“ abc”。该怎么做? 输入为1,输出为abc。

听起来您只想要:

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
}

有什么理由不只是使用Dictionary<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
}

为什么不使用字典? http://msdn.microsoft.com/zh-CN/library/xfhwa508.aspx

在我看来,这可以解决您的问题,并且更容易使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM