gpt4 book ai didi

c# - Dictionary.ContainsValue() 总是返回 true

转载 作者:行者123 更新时间:2023-11-30 14:24:22 24 4
gpt4 key购买 nike

我有一本映射到摩尔斯电码的所有字母表

Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("a", ".-");
data.Add("b", "-...");
data.Add("c", "-.-.");
data.Add("d", "-..");
data.Add("e", ".");
data.Add("f", "..-.");
data.Add("g", "--.");
data.Add("h", "....");
data.Add("i", "..");
data.Add("j", ".---");
data.Add("k", "-.-");
data.Add("l", ".-..");
data.Add("m", "--");
data.Add("n", "-.");
data.Add("o", "---"); and so on..

我正在尝试检查字典中是否存在现有摩尔斯电码的子字符串。

 foreach (var item in arraylist)
{

int smallcount=0;
int startIndex = 0;
//check if this combination exists for morse code
for(int w=0;w<shortInput;w++)
{
int substringLength=Convert.ToInt32(item[w].ToString());
string sub = morsecode.Substring(startIndex, substringLength);
if (data.ContainsValue(sub)) ;
{
smallcount++;

}
startIndex = startIndex + substringLength;
}

if(smallcount==shortInput)
{ count++; }


}

此处 data.ContainsValue(sub) 始终返回 true,即使字典中不存在该值也是如此。 Code Snapshot

谁能告诉我是否遗漏了什么?

最佳答案

ContainsValue 实际上并没有返回 true,但是您在 if 语句之后有一个分号。这意味着将始终执行以下 block ,因为它不是有条件地执行的。它得到如下处理:

if (data.ContainsValue(sub))
{
}
{
smallcount++;
}

取而代之的是,删除分号,这样您就可以在 if 语句后面直接添加一个代码块,如下所示:

if (data.ContaisnValue(sub))
{
smallcount++;
}

关于c# - Dictionary.ContainsValue() 总是返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41320164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com