Search for dictionary values

I have a dictionary containing Product values ​​with properties of type description . In the textbox1_textchanged handler textbox1_textchanged I want to search for Products in the dictionary that have specific text in the description .

I tried this:

 var values = (from pv in mydictionary where pv.Value.description.Contains(textBox1.Text) select pv.Value); 

This code does not work because the second key pressed, the var values ​​are empty.

All the examples I found look at the keys, but I need to look up the dictionary values.

+4
source share
4 answers

However, you have invalid code. You are trying to filter out values ​​that have a specific description, but you are missing a key element. You need to add the where clause to complete it.

 var values = from pv in mydictionary where pv.Value.description.Contains(textBox1.Text) select pv.Value; 

The best way to write this, however, is to simply look at the meaning of the dictionary.

 var values = from value in mydictionary.Values // Note: we're looking through the values only, // not all the key/value pairs in the dictionary where value.description.Contains(textBox1.Text) select value; 

To make it case insensitive, you can try using String.IndexOf() , as this is one of the few comparisons that a search could do, ignoring the case.

 var values = from value in mydictionary.Values where value.description .IndexOf(textBox1.Text, StringComparison.OrdinalIgnoreCase) != -1 // any value that isn't `-1` means it contains the text // (or the description was empty) select value; 
+6
source

Try

 var values = mydictionary.Where(k => k.Value.description.Contains(textBox1.Text)) .Select(k => k.Value); 
+2
source

Change the where clause to:

 where value != null && value.description != null && value.description.Contains(textBox1.Text) 
0
source

Another thing you might want to consider is that the string.Contains method will perform case-sensitive searches.

 var str = "The quick brown fox blah"; var test1 = "quick"; var test2 = "Quick"; Console.WriteLine(string.Format("{0} CONTAINS {1} = {2}", str, test1, str.Contains(test1))); Console.WriteLine(string.Format("{0} CONTAINS {1} = {2}", str, test2, str.Contains(test2))); //Output The quick brown fox blah CONTAINS quick = True The quick brown fox blah CONTAINS Quick = False 

If you cannot use case insensitive for both of them to return true, you must first put the strings in lowercase ...

 Console.WriteLine(string.Format("{0} CONTAINS {1} = {2}", str, test1, str.ToLower().Contains(test1.ToLower()))); Console.WriteLine(string.Format("{0} CONTAINS {1} = {2}", str, test2, str.ToLower().Contains(test2.ToLower()))); //Output The quick brown fox blah CONTAINS quick = True The quick brown fox blah CONTAINS Quick = True 
-1
source

All Articles