I have a dictionary that contains Product
values with properties like description
.
In a textbox1_textchanged
handler, I want to search the Products in the dictionary that has certain text within the description
.
I've tried this:
var values = (from pv in mydictionary
where pv.Value.description.Contains(textBox1.Text)
select pv.Value);
This code isn't working because the second key I pressed values var values is empty.
All the exa开发者_开发问答mples I found are searching through the keys but I need to search through the values of the dictionary.
What you have isn't valid code however. You are trying to filter the values that have a certain description but you're 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;
A better way to write this however would be to just look at the values 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 could try using String.IndexOf()
since it's one of the few comparisons that could do the search 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;
Try
var values = mydictionary.Where(k => k.Value.description.Contains(textBox1.Text))
.Select(k => k.Value);
Change the where clause to:
where value != null && value.description != null && value.description.Contains(textBox1.Text)
One other thing you may want to consider is that the string.Contains method will do a case sensitive search.
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 cant a case insensitive search so that both of the above would return true you should put the strings in lower case first ...
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
精彩评论