AC25
AC25

Reputation: 423

linq getting key from list keyvalue pair

this is seems simple, but I have a list of keyvalue pairs and a linq statement trying to get the the key, I dont understand why this dosent work Ex

   List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();

list contains values: 1, test1 | 2, test2 | 3, test3 as data my linq statement is:

string Key = list.AsEnumerable(x => x.Value == "test2").Select(x => x.Key).ToString();

seems simple enough to work but dosent?

Upvotes: 0

Views: 1694

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can use FirstOrDefault

var pair = list.FirstOrDefault(x => x.Value == "test2");
if(pair != null)
     string Key = pair.Key.ToString();

This is much safer than First and Single because it won't throw exception if there is no KeyValuePair with a given Value or there are more than one elements with a given Value.

Upvotes: 1

Cory Nelson
Cory Nelson

Reputation: 29981

To get a single value's key, you'd do:

string Key = list.Single(x => x.Value == "test2").Key.ToString();

What you've written should not compile. AsEnumerable() does not have an overload taking a predicate.

If it did compile, it would almost certainly not give you what you intended as you're calling ToString() on an IEnumerable<int>, which would return that type's name and not the Single() value or First() value in the enumeration.

Upvotes: 1

Related Questions