包含和等于(==)之间的差异

3 c# dictionary

我有一个Dictionary属性

 public Dictionary<string, bool> SearchType { get; set; }
Run Code Online (Sandbox Code Playgroud)

这个词典有4个键和4个键值.现在我将它们带到SearchType的变量,如果值为true

var searchTypes = searchDetail.SearchType.Where(x => x.Value == true).ToList();
Run Code Online (Sandbox Code Playgroud)

在这里,我从下面的代码检查了密钥是CKBinstituteType或CKBstate等

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

    }
 }
Run Code Online (Sandbox Code Playgroud)

或尝试这种方式(使用相同的操作而不是包含)

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

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

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


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

    }                   
}
Run Code Online (Sandbox Code Playgroud)

它们之间有什么区别?哪一个对我的情况有好处?(如性能,代码标准等)

Hab*_*bib 6

他们之间有什么不同?

这两个, ContainsEquals使用字符串比较.由于您Key的类型为string,因此Contains将检查传递的参数是否为键的一部分,而Equals将完整的字符串与相等性进行比较.

哪一个对我的情况有好处?(如性能,代码标准等)

使用ContainsKey方法,而不是字符串equals或contains.在foreach循环中使用Contains和Equals ,在那里比较Key哪个是string with ContainsEquals.您不需要迭代字典中的每个项目.如果你试图通过Key访问它,它是关于进行线性搜索,复杂性O(n)与使用复杂性进行字典查找O(1)

你可以使用ContainsKeyLike

if (SearchType.ContainsKey("CKBinstituteType"))
{
}
Run Code Online (Sandbox Code Playgroud)

目前您正在将您的词典转换为列表,我不确定您的词典是否真的需要列表然后进行线性搜索.如果你真的必须根据true值过滤掉Dictionary,那么将结果集投影到字典中然后使用ContainsKey如下:

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

}
Run Code Online (Sandbox Code Playgroud)

  • Yeap是最好的选择. (2认同)