DefColin DefColin - 22 days ago 10
C# Question

How to check dictionary if string value exist for conditional comparison

if I want use dictionary with given values for conditional comparison in if-statement to pass implementation but avoid if-statement for listing of this values and get it from dictionary. So how to check dictionary, which contains 400 strings, if string value exist:

Dictionary<int, string> set1 = new Dictionary<int, string>()
{{ 1, "string1" }, { 2, "string2" } ... }; // 400 values


So seems like this way is wrong:

string str = "string1";

if (set1.ContainsKey(str) == true)
{
Console.WriteLine("Contains");
}
else
{
Console.WriteLine("Does Not Contains");
}


To get result for further condition

Jim Jim
Answer

ContainsValue(value);

string str = "string1";

if (set1.ContainsValue(str) == true)
{
     Console.WriteLine("Contains");
}
else
{
     Console.WriteLine("Does Not Contains");
}

or with linq:

using System.Linq;
...
string str = "string1";

if (set1.Values.Any(x => x == str))
{
     Console.WriteLine("Contains");
}
else
{
     Console.WriteLine("Does Not Contains");
}
Comments