Reputation: 658
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?
Upvotes: 15
Views: 35700
Reputation: 1259
One of the many possible solutions:
List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>()
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b")
};
var pair = list.FirstOrDefault(x => x.Value == "b");
// or you can also use list.Find(x => x.Value == "b");
Console.WriteLine(pair.Value);
Console.WriteLine(pair.Key);
Upvotes: 3
Reputation: 2970
Use this:
d.FirstOrDefault(x=>x.Value == "yoursearchvalue").Key;
Upvotes: 1
Reputation: 30813
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;
Upvotes: 5
Reputation: 27357
You'd write this:
var result = d.Where(kvp => kvp.Value == "something");
result
would contain all the KeyValuePair
s with a value of "something"
Upvotes: 19