int3
int3

Reputation: 658

Find a KeyValuePair inside a 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?

Upvotes: 15

Views: 35700

Answers (4)

IMujagic
IMujagic

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

Chaos Legion
Chaos Legion

Reputation: 2970

Use this:

d.FirstOrDefault(x=>x.Value == "yoursearchvalue").Key;

Upvotes: 1

Ian
Ian

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

Rob
Rob

Reputation: 27357

You'd write this:

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

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

Upvotes: 19

Related Questions