Serializing an XML Dictionary with a Custom IEqualityComparer

I want to serialize a dictionary that has a custom IEqualityComparer.

I tried using DataContractSerializer, but I cannot get Comparer serialization.

I cannot use BinaryFormatter because of this .

I can always do something like:

var myDictionary = new MyDictionary(deserializedDictionary, myComparer); 

But that means that I will need twice as much memory as the dictionary uses.

+3
source share
2 answers

I just read the error report ...

Binary serialization is not performed for a graphic object with more than 13.2 million objects.

If you have a long schedule, you can always have problems.

Do you want to try an alternative serializer? "protobuf-net" is a custom binary serializer after the Google protocol buffer format and can work for large sets, especially in the "group" mode.

0
source

Why does custom Comparer even need to be serialized? Here is an example that works for me.

  using System;
 using System.Collections.Generic;
 using System.Runtime.Serialization;
 using System.IO;

 public class MyKey {
     public string Name {get;  set;  }
     public string Id {get;  set;  }
 }

 public class MyKeyComparer: IEqualityComparer {
     public bool Equals (MyKey x, MyKey y) {
         return x.Id.Equals (y.Id);
     }
     public int GetHashCode (MyKey obj) {
         if (obj == null) 
             throw new ArgumentNullException ();

         return ((MyKey) obj) .Id.GetHashCode ();
     }
 }

 public class MyDictionary: Dictionary {
     public MyDictionary ()
         : base (new MyKeyComparer ())
     {}
 }

 class Program {
     static void Main (string [] args) {
         var myDictionary = new MyDictionary ();
         myDictionary.Add (new MyKey () {Name = "MyName1", Id = "MyId1"}, "MyData1");
         myDictionary.Add (new MyKey () {Name = "MyName2", Id = "MyId2"}, "MyData2");

         var ser = new DataContractSerializer (typeof (MyDictionary));

         using (FileStream writer = new FileStream ("Test.Xml", FileMode.Create))
             ser.WriteObject (writer, myDictionary);

         using (FileStream reader = new FileStream ("Test.Xml", FileMode.Open))
             myDictionary = (MyDictionary) ser.ReadObject (reader);
     }
 }

0
source

All Articles