Joe C
Joe C

Reputation: 13

Dictionary lookup using a variable

Can a dictionary of type string and CheckBox be parsed by a variable string in such a way that should the variable string find a dictionary entry that matches it, it will set the corresponding checkbox to true?

Upvotes: 1

Views: 229

Answers (4)

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

I would use TryGetValue to reduce the accesses to the dictionary:

Dictionary<string, CheckBox> aDict;
// your code here
CheckBox tmp;
if (aDict.TryGetValue(stringToSearch, out tmp))
    tmp.Checked = true;

Upvotes: 0

Kyle W
Kyle W

Reputation: 3752

It seems like you're asking: I have a Dictionary. I want to set the corresponding checkbox to true for a given string. That can be accomplished by the following

Dictionary<string, CheckBox> dictionary = <elided>;
CheckBox checkBox = dictionary[valueToSearch];
checkBox.Checked = true;

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

Yes, you can achieve that using following code. Let's say you have myDictionary<string, CheckBox> and a string stringToCheck which contains that value you want to find in the dictionary You can do something like this

string stringToCheck = "something";

if(myDictionary.ContainsKey(stringToCheck))
{
    myDictionary[stringToCheck].Checked = true;
}

Upvotes: 4

Paddy
Paddy

Reputation: 33857

Is Dictionary.ContainsValue what you are looking for?

http://msdn.microsoft.com/en-us/library/a63811ah.aspx

Upvotes: 0

Related Questions