HashSet<string> with StringComparer.InvariantCultureIgnoreCase

530 views
Skip to first unread message

David Boike

unread,
Jun 13, 2012, 5:41:50 PM6/13/12
to rav...@googlegroups.com
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?

Matt Warren

unread,
Jun 14, 2012, 6:01:35 AM6/14/12
to rav...@googlegroups.com
You can change the default behaviour by making a CustomerJsonSerializer and registering it with the doc store, there's a nice example here https://groups.google.com/d/msg/ravendb/e6ScMqPwpBs/Ib1n6poes1oJ. It not exactly the same scenario as yours, but should give you an idea of the basics involved.

Oren Eini (Ayende Rahien)

unread,
Jun 14, 2012, 8:08:32 AM6/14/12
to rav...@googlegroups.com
You can make it work with a Document Conversion Listener, or by modifying the serializer using CustomizeJsonSerializer
Reply all
Reply to author
Forward
0 new messages