Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Value of List of KeyValuePair

Tags:

c#

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?

like image 349
Devi Avatar asked Jul 09 '12 07:07

Devi


People also ask

How do you find the value of key value pairs?

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.

What is the default value of KeyValuePair?

default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .

Can KeyValuePair have duplicate keys?

[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<> .

What is key-value pair in C#?

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.


2 Answers

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.

like image 103
pangabiMC Avatar answered Oct 16 '22 12:10

pangabiMC


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; 
like image 41
Daniel Sklenitzka Avatar answered Oct 16 '22 13:10

Daniel Sklenitzka