使用 List.Contains 方法查找字符串 returns false 但手动比较 return true

Using List.Contains method to find a string returns false but manual comparison return true

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

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

您还没有说明您的列表是什么类型,但是如果它是 ArrayListList<object>,比较将给出与 List<string> 不同的结果,因为 Compare 方法将比较对象而不是字符串。

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

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

s1 += "B";

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

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

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