![](/img/trans.png)
[英]to get a KeyValuePair from a List of KeyvaluePairs with the minimum value
[英]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.