What is the different between of them?
Both, Contains
and Equals
are using string comparison. Since your Key
is of type string, Contains
will check if the passed parameter is part of the key, whereas Equals
compares the complete string for equality.
Which one is good for my situation? (like performance, code standard,etc)
Use ContainsKey
method , instead of string equals or contains.
Contains and Equals are used inside the foreach
loop, where you are comparing the Key
which is a string
with Contains
and Equals
. You don't need to iterate each item in the dictionary. If you are trying to access it through Key, It is about doing a Linear search with complexity of O(n)
vs doing dictionary lookup with complexity O(1)
You can use ContainsKey
Like
if (SearchType.ContainsKey("CKBinstituteType"))
{
}
Currently you are converting your Dictionary to List, I am not sure if there is really a need your dictionary to a List and then do a linear search. If you really have to filter out the Dictionary based on true
values then project the result set into a dictionary and then use ContainsKey
like:
var searchTypes = searchDetail.SearchType.Where(r => r.Value == true)
.ToDictionary(r => r.Key, r => r.Value);
if (searchTypes.ContainsKey("CKBinstituteType"))
{
}
if (searchTypes.ContainsKey("CKBstate"))
{
}
if (searchTypes.ContainsKey("CKBlocation"))
{
}
if (searchTypes.ContainsKey("CKBdistance"))
{
}