1

I'm trying to find string in dictionary with pair values to find its integer value. Important to find through the string and then get its integer, not vice-versa. 1000 strings list "string" and integer:

Dictionary<string, int> Dict = new Dictionary<string, int>();

and now I want find specific string, some input, which is exist in Dict:

 string findStr = "hello world";

This way I got all strings which start with "hello...":

 var result = Dict.Where(pair => pair.Key.StartsWith(findStr) && pair.Value > 0);

and this way just nothing:

var result = Dict.Where(pair => pair.Key.Equals(findStr) && pair.Value > 0);  

I'm not sure how to go further to get desired result:

To find equal string in my Dictionary and get its pair integer value.

2 Answers2

0

You should be reading a dictionary like this dict[key], which will give you O(1) access. You can either check if the key exists first either by using ContainsKey(key) method or try to read the value by TryGetValue

AD.Net
  • 13,352
  • 2
  • 28
  • 47
  • TryGetValue Hello, I'm going to mark it as answer, TryGetValue works well –  Dec 28 '16 at 17:09
0
var result = Dict.Where(pair => pair.Key==findStr && pair.Value > 0); 

see the difference between .equals and == here C# difference between == and Equals()

Community
  • 1
  • 1
Mehul Patel
  • 1,084
  • 2
  • 12
  • 28
  • hello, this way also should work for sure, but in my case I got 0 in result if I use it in followed condition, but with event for example it works well. So I'm going to mark AD.Net answer as TryGetValue is more useful for my case, but this answer is also good and useful for different case –  Dec 28 '16 at 17:14
  • Using `.Where` will give you very poor performance with a dictionary, when you use that you now have the performance as if you had a `List>` which is much slower than a dictionary. – Scott Chamberlain Dec 28 '16 at 18:13