2

I am using MultiValueDictionary(String,string) in my project (C# - VS2012 - .net 4.5), which is a great help if you want to have multiple values for each key, but I can't serialize this object with protobuf.net.

I have serialized Dictionary(string,string) with Protobuf with ease and speed and MultiValueDictionary inherits from that generic type; so, logically there should be no problem serializing it with the same protocol.

Does any one know a workaround?

This is the error message when I execute my codes:

System.InvalidOperationException: Unable to resolve a suitable Add method for System.Collections.Generic.IReadOnlyCollection

Alirezaaa
  • 45
  • 4

1 Answers1

0

Do you realy need a dictionary? If you have less than 10000 items in your dictionary you can also use a modified list of a datatype..

    public class YourDataType
    {
        public string Key;

        public string Value1;

        public string Value2;

        // add some various data here...
    }

    public class YourDataTypeCollection : List<YourDataType>
    {
        public YourDataType this[string key]
        {
            get
            {
                return this.FirstOrDefault(o => o.Key == key);
            }
            set
            {
                YourDataType old = this[key];
                if (old != null)
                {
                    int index = this.IndexOf(old);
                    this.RemoveAt(index);
                    this.Insert(index, value);
                }
                else
                {
                    this.Add(old);
                }
            }
        }
    }

Use the list like this:

    YourDataTypeCollection data = new YourDataTypeCollection();

    // add some values like this:
    data.Add(new YourDataType() { Key = "key", Value1 = "foo", Value2 = "bar" });

    // or like this:
    data["key2"] = new YourDataType() { Key = "key2", Value1 = "hello", Value2 = "world" };
    // or implement your own method to adding data in the YourDataTypeCollection class

    XmlSerializer xser = new XmlSerializer(typeof(YourDataTypeCollection));

    // to export data
    using (FileStream fs = File.Create("YourFile.xml"))
    {
        xser.Serialize(fs, data);
    }

    // to import data
    using (FileStream fs = File.Open("YourFile.xml", FileMode.Open))
    {
        data = (YourDataTypeCollection)xser.Deserialize(fs);
    }

    string value1 = data["key"].Value1;
Klaus Fischer
  • 125
  • 1
  • 6
  • Thanks @KlausFischer , my Dictionary contains more than 1.5 million elements and I am using this type for it's fast retrieval time. I have used many other types and MultiValueDictionary is by far the fastest! – Alirezaaa Aug 01 '15 at 08:31