0

I have a static dictionary that I need to use in my program.I have it loaded in a Dictionary and I was wondering how and where to store it so I can acces its values later the easiest way possible.

I was wondering of making xml file of it with a key->value pairs but I don't know exactly how to save it and format it so Later I can call it the way I can call my appSettings keys and values(using LINQ).

I just need to have it stored somewhere, as a resource why not, and every time I need a particular value for a key it takes no more than a line of code to get its value.

user2128702
  • 2,059
  • 2
  • 29
  • 74

1 Answers1

0

You could use LINQ2XML to create two methods for writing and reading the Dictionary object.

Storing the Dictionary (extend / change for your types) to a file:

private void storeXml(string location, Dictionary<int, string> data)
{
    var xml = new XElement("storage", 
                    data.Select(kv => new XElement("entry", 
                                new XElement("key", kv.Key), 
                                new XElement("value", kv.Value))));
    xml.Save(location);
}

Read data from a file and fill the dictionary object:

private Dictionary<int, string> readXml(string location)
{
    var data = new Dictionary<int, string>();

    var xml = XDocument.Load(location);
    foreach(var element in xml.Descendants("entry").ToList())
    {
        var key = int.Parse(element.Element("key").Value);
        var value = element.Element("value").Value;
        data.Add(key, value);
    }

    return data;
}

The code can be used like this:

var data = new Dictionary<int, string>();
data.Add(1, "one");
data.Add(2, "two");
data.Add(3, "three");
data.Add(4, "four");

var fileLocation = @"d:\temp\dictionary.xml";

storeXml(fileLocation, data);

var d = readXml(fileLocation);

The XML file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<storage>
    <entry>
        <key>1</key>
        <value>one</value>
    </entry>
    <entry>
        <key>2</key>
        <value>two</value>
    </entry>
    <entry>
        <key>3</key>
        <value>three</value>
    </entry>
    <entry>
        <key>4</key>
        <value>four</value>
    </entry>
</storage>
keenthinker
  • 7,645
  • 2
  • 35
  • 45