Search code examples
c#.netarraylistkeyvaluepair

How do i retrieve an Object stored in a ist in the form of KeyValuePair in C#?


I have the following List with KeyValuePair as the data.

using SerialPort as PORT
List<KeyValuePair<string, PORT>> myPortList = new List<KeyValuePair<string, PORT>>();

I have added elements to the list in the following manner

PORT sp1 = new PORT("COM1", 9200, Parity.None, 8, StopBits.One);
PORT sp2 = new PORT("COM4", 9200, Parity.None, 8, StopBits.One);
myPortList.Add(new KeyValuePair<string,PORT>("COM1",sp1));
myPortList.Add(new KeyValuePair<string,PORT>("COM4",sp2));

How do i get the SerialPort object stored in the list using the key?
Eg:
Need to retrieve value sp2 by using the key "COM4" from the list myPortList ?


Solution

  • You could use Linq:

    myPortList.Fist(kp => kp.Key.Equals("COM4"));
    

    If you can do, use Dictionary instead, itt will be more easy to get elements from it.

    Exemple for Dictionary:

    Dictionary<string, PORT> myPortDict = new Dictionary<string, PORT>();
    
    PORT sp2 = new PORT("COM4", 9200, Parity.None, 8, StopBits.One);
    myPortDict.Add("COM4",sp1);
    
    //then to retrive:
    
    dc.TryGetValue("COM4", out PORT myPort);
    
    //then use myPort