Reputation: 1352
This question might appear to be a duplicate and/or too boring, but I want to do this using this specific method.
When a user enters a string into a textbox I want to get this string key. So to do this I've created a dictionary which has n (n <= 15000) unique values. I want to get the key from this dictionary by value. The method below works well:
Dictionary<int, string> artikullar = new Dictionary<int, string>();
int key = (from elem in artikullar where elem.Value == txt_artikul.Text select elem).First().Key;
Before that I tried to use the First()
method to get the key:
int key = artikullar.AsParallel().First(new Func<KeyValuePair<int, string>, bool>(val => val == txt_artikul.Text)).Key;
But it throws this error:
Operator '==' cannot be applied to operands of type 'KeyValuePair' and 'string'
I haven't used this method before.
Any helpful comment or answer would be appreciated.
Upvotes: 2
Views: 8908
Reputation: 43946
Ehsan Sajjad is correct. But I'd like to add another point:
You said that the strings in your Dictionary
are unique. I don't know when you created the Dictionary
and if the data is rather static or dynamically changing all the time.
If it's rather static and the strings are unique, you may consider to create a reversed Dictionary
like this:
Dictionary<string, int> reversedDict = artikullar.ToDictionary(
kvp => kvp.Value,
kvp => kvp.Key);
and then use this for your lookup:
int key = reversedDict[txt_artikul.Text];
This may be faster than querying the original dictionary.
Upvotes: 7
Reputation: 62498
You have to change :
val => val == txt_artikul.Text
to:
val = > val.Value == txt_artikul.Text
you have instance of KeyValuePair
, you have to specify Value
in lambda expression to be compared.
Upvotes: 3