C#Hashset <string>包含错误返回false

时间:2016-09-16 04:43:52

标签: c# database string

我试图将从数据库填充的字符串的Hashset与对象的字符串属性进行比较。我知道它存在于hashset中,但它总是返回false。

奇怪的是,我写了一个测试程序,表现得如我所料。见下文

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;
    }
  }
}

另一方面,这不是。我必须为此编写自定义比较器吗?这不是自定义对象,我只是比较字符串。我知道字符串包含在哈希集中。

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

1 个答案:

答案 0 :(得分:0)

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