简体   繁体   中英

C# Hashset<string> Contains incorrectly returns false

I am trying to compare a Hashset of strings populated from a database against a string property from an object. I know that it exists in the hashset, but it is always returning false.

Oddly enough, I wrote a test program that behaves how I would expect. See Below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
    static void Main(string[] args)
    {
        string test = "A";
        HashSet<String>[] array = new HashSet<string>[1]; 
        array[0] = new HashSet<string>();
       Boolean isA = true;
       Boolean isB = false;
       array[0].Add("A");
        if (array[0].Contains(test) && isA || isB)
            if (test.Equals("A")) {
                Console.WriteLine("A");
            }
            return;
    }
  }
}

On the other hand, this does not. Do I have to write a custom comparator for this? This is not a custom object, I'm just comparing strings. I know that the string is contained in the hash set.

private readonly HashSet<string>[] cars = new HashSet<string>[5];

 for (int i = 0; i < cars.Length; i++)
        cars[i] = new HashSet<string>();

  foreach (DataRow dr in dt.Rows)
   {
        switch (dr[0].ToString())
         {
            case "1": 
              cars[0].Add(dr[1].ToString());
                            break;
          }
    }
bool test = cars[0].Contains("A"); //Always returns false

尝试添加cars[0].Add(dr[1].ToString().Trim().ToUpper())并检查。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM