User
User

Reputation: 1662

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.

Upvotes: 0

Views: 162

Answers (2)

RifRaf
RifRaf

Reputation: 29

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500595

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
}

Upvotes: 6

Related Questions