【问题标题】:Using List.Contains method to find a string returns false but manual comparison return true使用 List.Contains 方法查找字符串返回 false 但手动比较返回 true
【发布时间】:2017-11-30 20:48:40
【问题描述】:

我有一个字符串列表,我正在尝试确定其中一个是否与针线匹配。该字符串列表在第一个索引处包含针,我的代码具有以下行为:

listOfStrings.Contains(needle); // return false
listOfStrings[0] == needle; // return true

为什么 Contains 方法的行为与默认比较行为不同,我应该修改什么使其具有相同的行为?

为了更深入地了解我所面临的问题,我正在处理来自 WinForm 文本框的字符串。它们代表输入路径和目标文件夹。

        if (!destinationPath.EndsWith("\\"))
        {
            destinationPath += "\\";
        }
        List<string> inputDirectories = new List<string>(inputPaths.Length);
        foreach (string path in inputPaths)
        {
            inputDirectories.Add(Path.GetDirectoryName(path).ToLower());
        }

        bool comparison1 = inputDirectories[0] == Path.GetDirectoryName(destinationPath.ToLower()); // return true
        bool comparison2 = inputDirectories.Contains(Path.GetDirectoryName(destinationPath.ToLower())); // return false

【问题讨论】:

  • 我们需要一些例子来看看。信息不足。
  • 请给我们更多关于正在使用的字符串的信息。几个例子。
  • 不要让您寻求帮助的人不得不猜测问题所在;给出一个编译和演示问题的清晰、简短的示例
  • 我编辑了问题以提供精确的示例。

标签: c# .net string string-comparison


【解决方案1】:

你还没有说你的列表是什么类型,但是如果它是 ArrayListList&lt;object&gt; 比较将给出与 List&lt;string&gt; 不同的结果,因为 Compare 方法将比较对象而不是字符串.

要理解这一点,请尝试运行以下代码:

string s1 = "A";
string s2 = "AB";

s1 += "B";

Console.WriteLine(s1 == s2);  // True 
Console.WriteLine((object)s1 == (object)s2); // False

s1s2 在作为字符串比较时相等,但它们是不同的对象。

如果您已经在使用List&lt;string&gt; 并且正在寻找不区分大小写的包含,请尝试the accepted answer to this question 中的技术。

【讨论】:

  • 好的,我明白了,谢谢您的准确回答,是否有使用 List 根据字符串值而不是参考值比较字符串的方法?或者是否应该为此目的在 List 上使用 ArrayList?
  • @Toto:您应该使用 ArrayList 的唯一情况是您被时间旅行者绑架,带回过去,并被困在只有 C# 1.0 的世界中。始终使用泛型类型。
  • 这如何解释为什么在原始问题中 compare1 为真而 compare2 为假?
猜你喜欢
  • 2013-02-23
  • 2016-12-05
  • 2011-01-18
  • 2019-10-06
  • 2016-12-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
相关资源
最近更新 更多