How can i select the value from the List of keyvaluepair based on checking the key value
List<KeyValuePair<int, List<Properties>> myList = new List<KeyValuePair<int, List<Properties>>();
Here I want to get the
list myList[2].Value when myLisy[2].Key=5.
How can i achieve this?
In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method.
default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .
[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.
If you need to use the List anyway I'd use LINQ for this query:
var matches = from val in myList where val.Key == 5 select val.Value; foreach (var match in matches) { foreach (Property prop in match) { // do stuff } }
You may want to check the match for null.
If you're stuck with the List, you can use
myList.First(kvp => kvp.Key == 5).Value
Or if you want to use a dictionary (which might suit your needs better than the list as stated in the other answers) you convert your list to a dictionary easily:
var dictionary = myList.ToDictionary(kvp => kvp.Key); var value = dictionary[5].Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With