I need to have a model with a case-insensitive hash set.
public class MyModel
{
public MyModel()
{
Set = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
}
public HashSet<string> Set { get; set; }
}
And this is stored in JSON the same as an array or any other enumerable would be:
{
"Set": [
"Item0",
"Item1",
]
}
The problem comes when I load the model back from the database. The HashSet is constructed with the wrong comparer, and eventually you might get this:
{
"Set": [
"Item0",
"ITEM0",
"item0",
"iTeM0",
"Item1",
]
}
The only thing I can think of is to create a class that forces the comparer:
public class StringSetIgnoreCase : HashSet<string>
{
public StringSetIgnoreCase()
: base(StringComparer.InvariantCultureIgnoreCase)
{
}
}
Then I would use StringSetIgnoreCase as the type in my model instead of HashSet<string>.
But of course this has some problems:
- Only handles sets of strings
- And only the one type of string comparer
- Requires other model developers in my organization to know about this issue and this class - there isn't any way for me to hide it in the architecture for their own good.
Is there any better way to do this that addresses those concerns?