Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a KeyValuePair inside a List

Tags:

c#

list

Suppose I have

 List<KeyValuePair<int, string>> d

I know the string but I want to find its integer. How do I find the keyvaluepair inside this List?

like image 392
int3 Avatar asked May 20 '16 09:05

int3


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. The value of the key at the first level of the JSON document hierarchy will be obtained.

How do you check if a key-value pair exists in a List C#?

You can use IEqualityComparer<KeyValuePair<string, int>> .

What is KeyValuePair 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.

Can KeyValuePair have duplicate keys?

[C#] Dictionary with duplicate keys The 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<> .


2 Answers

You'd write this:

var result = d.Where(kvp => kvp.Value == "something");

result would contain all the KeyValuePairs with a value of "something"

like image 96
Rob Avatar answered Oct 12 '22 13:10

Rob


You could use LINQ Single or SingleOrDefault if the item is unique:

KeyValuePair<int, string> v = d.SingleOrDefault(x => x.Value == "mystring");
int key = v.Key;

If the item is not unique, then you could use LINQ Where:

var v = d.Where(x => x.Value == "mystring"); //the results would be IEnumerable

And if the item is not unique, but you want to get the first one among the non-unique items, use First or FirstOrDefault

var v = d.FirstOrDefault(x => x.Value == "mystring");
int key = v.Key;
like image 31
Ian Avatar answered Oct 12 '22 12:10

Ian