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?
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.
You can use IEqualityComparer<KeyValuePair<string, int>> .
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.
[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<> .
You'd write this:
var result = d.Where(kvp => kvp.Value == "something");
result
would contain all the KeyValuePair
s with a value of "something"
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;
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