Hardrock302 Hardrock302 - 1 month ago 5x
C# Question

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;
if (array[0].Contains(test) && isA || isB)
if (test.Equals("A")) {

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":
bool test = cars[0].Contains("A"); //Always returns false


Try to add with it cars[0].Add(dr[1].ToString().Trim().ToUpper()) and check.