How to get value by the help of key from KeyValuePair in C#

1k Views Asked by At
static private List<KeyValuePair<string, Employee>> employeesList = new List<KeyValuePair<string, Employee>>();

This is my generic KeyValuePair List that stores employee objects with employeeid as key. How to get value i.e Employee object with the help of the string key.

2

There are 2 best solutions below

2
GazTheDestroyer On
using System.Linq;

Employee employee = employeesList.FirstOrDefault(x => x.Key == employeeId).Value;

You'd be better off using a Dictionary though. That way you could look up the Id directly rather than iterating the list.

Employee employee = employoeesDictionary[employeeId];
0
Tolga Cakir On
var employee = employeesList.FirstOrDefault(x => x.Key == "").Value;

you can not use ? operator.