How do I save the complete dictionary locally and load it when needed?

I have a C # program that fetches data from a web page and then organizes the content in a dictionary. So far the program gets data from the internet every time I run it because there is no alternative data source. The problem is, if I am offline, I cannot get data, so I have no data to work with. Can I save the entire dictionary locally so that I can download it and run my analysis, even if I'm offline?

The dictionary for saving is myData:

Dictionary<string, itemdata> myData = new Dictionary<string, itemdata>();

      

where key is a string and represents the name of the item, and itemdata in turn is defined as:

public class itemdata
{
    // Fields
    public double itemWeight;
    public double itemSize;
    public double itemPrice;

    // class constructor
    public itemdata(double myItemWeight, double myItemSize, double myItemPrice)
    {
        itemWeight= myItemWeight;
        itemSize= myItemSize;
        itemPrice= myItemPrice;
    }

    // Public properties (read only access to these fields)
    public double myItemWeight
    {
        get { return itemWeight; }
    }

    public double myItemSize
    {
        get { return itemSize; }
    }

    public double myItemPrice
    {
        get { return itemPrice; }
    }
}

      

So, in my main class, I retrieve some data for some elements and then fill in:

itemdata myItemMap = new itemdata (itemWeight, itemSize, itemPrice)

      

and paste all the words into the dictionary:

myData.Add(itemName, myItemMap);

      

Once all the data has been recovered and organized into the myData dictionary, I would like this to be stored locally.

Thanks for all the suggestions you gave me. Saving to XML seems to be a good choice, but I would appreciate some clear example of how to work with my specific dictionary, as it is not just "one key and one value", but a somewhat more complex "one key with multiple values ​​/ fields ".

+3


source to share


2 answers


Another thing you can do is serialize it to XML using the built-in serializer. The type you will serialize must implement ISerializable. This is the only requirement. The good thing is .NET is going to take care of the rest for you.



+1


source


Typically you want a list of some custom class objects that allow the XmlSerializer to be used to save to XML. The dictionary is not directly serializable to XML. Here I am using an example:

class Program
{
  static void Main(string[] args)
  {
    var myData = new Dictionary<string, ExampleDataClass>()
    {
      { "First", new ExampleDataClass() { Name = "John", Surname = "Doe" } },
      { "Second", new ExampleDataClass() { Name = "Foo", Surname = "Bar" } }
    };
    var fileName = @"C:\MyPath\dict.xml";
    myData.SaveToXml(fileName);
    myData.Clear();
    myData = MySerializer.LoadFromXml<string, ExampleDataClass>(fileName);
  }
}

public class ExampleDataClass
{
  public string Name { get; set; }
  public string Surname { get; set; }
}

public class KeyValue<TKey, TValue>
{
  public TKey Key { get; set; }
  public TValue Value { get; set; }
}

static class MySerializer
{
  public static void SaveToXml<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string fileName)
  {
    var serializer = new XmlSerializer(typeof(List<KeyValue<TKey, TValue>>));

    using (var s = new StreamWriter(fileName))
    {
      serializer.Serialize(s, dictionary.Select(x => new KeyValue<TKey, TValue>() { Key = x.Key, Value = x.Value }).ToList());
    }
  }

  public static Dictionary<TKey, TValue> LoadFromXml<TKey, TValue>(string fileName)
  {
    var serializer = new XmlSerializer(typeof(List<KeyValue<TKey, TValue>>));

    using (var s = new StreamReader(fileName))
    {
      var list = serializer.Deserialize(s) as List<KeyValue<TKey, TValue>>;
      return list.ToDictionary(x => x.Key, x => x.Value);
    }
  }
}

      

This will save the sample data in an XML file like this:



<?xml version="1.0" encoding="utf-8"?>
<ArrayOfKeyValueOfStringExampleDataClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <KeyValueOfStringExampleDataClass>
    <Key>First</Key>
    <Value>
      <Name>John</Name>
      <Surname>Doe</Surname>
    </Value>
  </KeyValueOfStringExampleDataClass>
  <KeyValueOfStringExampleDataClass>
    <Key>Second</Key>
    <Value>
      <Name>Foo</Name>
      <Surname>Bar</Surname>
    </Value>
  </KeyValueOfStringExampleDataClass>
</ArrayOfKeyValueOfStringExampleDataClass>

      

The sample code does not resolve any exceptions and invalid data.

+1


source







All Articles