Make HashSet<string> case-insensitive

C#.NetHashset

C# Problem Overview


I have method with HashSet parameter. And I need to do case-insensitive Contains within it:

public void DoSomething(HashSet<string> set, string item)
{
    var x = set.Contains(item);
    ... 
}

Is it any way to make existing HashSet case-insensitive (do not create new one)?

I'm looking for solution with best perfomance.

Edit

Contains can be called multiple times. So IEnumerable extensions are not acceptable for me due to lower perfomance than native HashSet Contains method.

Solution

Since, answer to my question is NO, it is impossible, I've created and used following method:

public HashSet<string> EnsureCaseInsensitive(HashSet<string> set)
{
    return set.Comparer == StringComparer.OrdinalIgnoreCase
           ? set
           : new HashSet<string>(set, StringComparer.OrdinalIgnoreCase);
}

C# Solutions


Solution 1 - C#

The HashSet<T> constructor has an overload that lets you pass in a custom IEqualityComparer<string>. There are a few of these defined for you already in the static StringComparer class, a few of which ignore case. For example:

var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
set.Add("john");
Debug.Assert(set.Contains("JohN"));

You'll have to make this change at the time of constructing the HashSet<T>. Once one exists, you can't change the IEqualityComparer<T> it's using.


Just so you know, by default (if you don't pass in any IEqualityComparer<T> to the HashSet<T> constructor), it uses EqualityComparer<T>.Default instead.


Edit

The question appears to have changed after I posted my answer. If you have to do a case insensitive search in an existing case sensitive HashSet<string>, you will have to do a linear search:

set.Any(s => string.Equals(s, item, StringComparison.OrdinalIgnoreCase));

There's no way around this.

Solution 2 - C#

You can not magically make case-sensetive HashSet (or Dictionary) to behave in case-insensitive way.

You have to recreate one inside your function if you can not rely on incoming HashSet to be case-insensitive.

Most compact code - use constructor from existing set:

var insensitive = new HashSet<string>(
   set, StringComparer.InvariantCultureIgnoreCase);

Note that copying HashSet is as expensive as walking through all items, so if your function does just on search it would be cheaper (O(n)) to iterate through all items. If your function called multiple times to make single case-insensitive search you should try to pass proper HashSet to it instead.

Solution 3 - C#

The HashSet is designed to quickly find elements as per its hashing function and equality comparator. What you are asking for is really to find an element matching "some other" condition. Imagine that you have a Set<Person> objects that uses only Person.Name for comparison and you need to find an element with some given value of Person.Age.

The point is you need to iterate over the contents of the set to find the matching elements. If you are going to be doing this often you might create a different Set, in you case using a case-insensitive comparator but then you would have to make sure that this shadow set is in sync with the original.

The answers so far are essentially variations of the above, I thought to add this to clarify the fundamental issue.

Solution 4 - C#

Assuming you've got this extension method:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
    return new HashSet<T>(source);
}

You can just use this:

set = set.Select(n => n.ToLowerInvariant()).ToHashSet();

Or, you could just do this:

set = new HashSet(set, StringComparer.OrdinalIgnoreCase); 
//or InvariantCultureIgnoreCase or CurrentCultureIgnoreCase

Solution 5 - C#

The constructor of HashSet can take an alternative IEqualityComparer that can override how equality is determined. See the list of constructors here.

The class StringComparer contains a bunch of static instances of IEqualityComparers for strings. Particularly, you're probably interested in StringComparer.OrdinalIgnoreCase. Here is the documentation of StringComparer.

Note that another constructor takes in an IEnumerable, so you can construct a new HashSet from your old one, but with the IEqualityComparer.

So, all together, you want to convert your HashSet as follows:

var myNewHashSet = new HashSet(myOldHashSet, StringComparer.OrdinalIgnoreCase);

Solution 6 - C#

If you want to leave the original, case-sensitive version in place, you could just query it with linq with case insensitivity:

var contains = set.Any(a => a.Equals(item, StringComparison.InvariantCultureIgnoreCase));

Solution 7 - C#

You can now use

set.Contains(item, StringComparer.OrdinalIgnoreCase);

without needing to re-create you HashSet

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwishmasterView Question on Stackoverflow
Solution 1 - C#Timothy ShieldsView Answer on Stackoverflow
Solution 2 - C#Alexei LevenkovView Answer on Stackoverflow
Solution 3 - C#Miserable VariableView Answer on Stackoverflow
Solution 4 - C#It'sNotALie.View Answer on Stackoverflow
Solution 5 - C#Ben ReichView Answer on Stackoverflow
Solution 6 - C#eouw0o83hfView Answer on Stackoverflow
Solution 7 - C#ElanisView Answer on Stackoverflow