Search code examples
c#listcontainkeyvaluepair

How do I retrieve a Value from a KeyValuePair inside a List?


I have the following list and I need to run a Contains() or similar method on it to retrieve the value associated with a specific key. How would I do this? I've searched everywhere and tried many things but I can't seem to figure it out.

List<KeyValuePair<string, int>> shopInventory = new List<KeyValuePair<string, int>>();

I would assume it's something along the lines of:

shopInventory.Contains((KeyValuePair<string, int>

If I've neglected to include any important information I'll be happy to provide it.


Solution

  • You can use LINQ.

    return shopInventory.First(c => c.Key == key).Value;
    

    You might want error handling on top of that too, of course.

    You could also ToDictionary if you're using it a lot.