[英]Get the value from list
I create the list like 我创建列表像
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"));
How to select the value from this list. 如何从此列表中选择值。 Which means I need to pass 1 to the list and need to take the equal value "abc".How to do this?
这意味着我需要将1传递给列表,并且需要使用相等的值“ abc”。该怎么做? input is 1,output is abc.
输入为1,输出为abc。
It sounds like you just want: 听起来您只想要:
var value = list.First(x => x.Key == input).Value;
That's if you're sure the key will be present. 如果您确定该密钥将存在。 It's slightly trickier otherwise, partly because
KeyValuePair
is a struct. 否则,这会有点棘手,部分是因为
KeyValuePair
是一个结构。 You'd probably want: 您可能想要:
var pair = list.FirstOrDefault(x => x.Key == input);
if (pair.Key != null)
{
// Yes, we found it - use pair.Value
}
Any reason you're not just using a Dictionary<string, string>
though? 有什么理由不只是使用
Dictionary<string, string>
? That's the more natural representation of a key/value pair collection: 那是键/值对集合的更自然的表示:
var dictionary = new Dictionary<string, string>
{
{ "1", "abc" },
{ "2", "def" },
{ "3", "ghi" }
};
Then: 然后:
var value = dictionary[input];
Again, assuming you know the key will be present. 同样,假设您知道该密钥将存在。 Otherwise:
除此以外:
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
}
Why are you not using a Dictionary? 为什么不使用字典? http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
http://msdn.microsoft.com/zh-CN/library/xfhwa508.aspx
It seems to me this would solve your problem, and it's much easier to use. 在我看来,这可以解决您的问题,并且更容易使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.