简体   繁体   中英

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? input is 1,output is 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. 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? 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

It seems to me this would solve your problem, and it's much easier to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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