Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between contains and equal(==)

Tags:

c#

dictionary

I have a Dictionary property

 public Dictionary<string, bool> SearchType { get; set; }

this Dictionary has 4 keys and 4 values for that keys. Now I take them to a variable from SearchType, if the values are true

var searchTypes = searchDetail.SearchType.Where(x => x.Value == true).ToList();

Here I checked the key is CKBinstituteType or CKBstate and etc, from the below code

foreach (var searchType in searchTypes)
{
    if (searchType.Key.Contains("CKBinstituteType"))
    {

    }
    if (searchType.Key.Contains("CKBstate"))
    {

    }
    if (searchType.Key.Contains("CKBlocation"))
    {

    }
    if (searchType.Key.Contains("CKBdistance"))
    {

    }
 }

or tried with this way (used equal operation instead of contains)

foreach (var searchType in searchTypes)
{
    if (searchType.Key == "CKBinstituteType")
    {

    }
    if (searchType.Key == "CKBstate")
    {

    }
    if (searchType.Key == "CKBlocation")
    {


    }
    if (searchType.Key == "CKBdistance")
    {

    }                   
}

What is the difference between of them? Which one is good for my situation? (like performance, code standard,etc)


1 Answers

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"))
{

}
like image 61
Habib Avatar answered Oct 29 '25 21:10

Habib