1

For example, in a file of my project I have Dictionaries.cs containing:

 public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.

Aroueterra
  • 336
  • 3
  • 18
  • This is possible. You could serialize your initial dictionary into a JSON string and create a text file for that if the text file does not exist during start-up. Also you can load the content of the text file and deserialize the JSON string back into your dictionary. Your approach could be serializing/deserializing an array or list of dictionaries. – jegtugado Jun 09 '17 at 02:10

3 Answers3

1

how they differentiate a key from a value

From the format. If you try any of those steps, the resulting file clearly differentiate between the keys & values.

I don't think I will be able to access my DictionaryCheckup class through this

You will be able to. If you use JavaScriptSerializer, just make sure you follow the requirement, similar requirement exist for JSON.NET. Of course, the Linq to XML answer have to be modified if you have complex type.

write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime?

Yes, you can just deserialize the collection at once, no need to create the empty collection and fill it one by one. This is true for all serialization method.

Martheen
  • 5,198
  • 4
  • 32
  • 55
  • I got to actually trying the code in the link I posted and managed to run it without errors. Generating a file: I can see that my file looks something like this: `{"12":{"theDescription":"Account","theClass":""},"13":{"theDescription":"Span_Year","theClass":""},` Now, I run the deserialization to return it to my dictionary, and that also ran without errors, however, I'm not exactly sure what became of it. If I modify the text file that I serialized to, and read it back in, what happens to the dictionary it was based on? Is this a new dictionary? Were the values simply added to the old one? – Aroueterra Jun 09 '17 at 05:06
  • It will be replaced – Martheen Jun 09 '17 at 05:07
  • Ah, I see, very good. So I call it the same as I would if it were the original one? It's hard to tell since the debugger doesn't get updated with this information. – Aroueterra Jun 09 '17 at 05:08
  • Yes, as long as you follow the format, the deserializer will accept any data happily. – Martheen Jun 09 '17 at 05:09
1

You could use serialisation to convert your dictionary to a json string, then write it down in a text file. Then you can read up that same file and deserialise the json string to get your dictionary back. Here's an example :

public static string SerializeToJSON<T>(T obj) {
    return new JavaScriptSerializer().Serialize(obj);
}

public static T DeserializeJSON<T>(string json) {
    return new JavaScriptSerializer().Deserialize<T>(json);
}

// Fake path for the example
string path = "~/myFile.json";

// Instanciates a fake dictionary for the example.
Dictionary<string,string> myDict = new Dictionary<string,string>() { new KeyValuePair("A","1") };

// Using serialisation, we save the content of our dictionary into a text file.
string json = SerializeToJSON<Dictionary<string,string>>(myDict);
File.WriteAllText(path, json);

// Then with deserialisation, we get back our old dictionary. 
Dictionary myOtherDict = Dictionary<string,string>DeserializeJSON<Dictionary<string,string>>(File.ReadAllText(path));
CBinet
  • 187
  • 2
  • 12
1

You can use JSON.Net to serialize your dictionaries to JSON, which can then be read and written to the file.

JSON is simply a way to format .Net objects in a manner that can be stored (e.g. in a file). It is based on JavaScript's syntax, but has nothing to do with the web directly.

Something like this should work:

// Default dictionary
Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
{
    {180000, new DictionaryCheckup {theGrouping = "H"}},
    {180001, new DictionaryCheckup {theGrouping = "H"}},
    {180303, new DictionaryCheckup {theGrouping = "H"}},
};

// Then when we plan on loading our dictionary...

// Write our our default JSON if no config file exists
if (!File.Exists("H.json"))
{
    using (var stream = new StreamWriter(File.Create("H.json")))
    {
        // Convert our "H" dictionary into JSON
        var json = JsonConvert.SerializeObject(H, Formatting.Indented);

        // Write the JSON to the file
        stream.Write(json);
        stream.Flush();
    }
}
// Read the JSON that our user has configured
else
{
    using (var stream = new StreamReader(File.OpenRead("H.json")))
    {
        // Read our JSON from the file
        var json = stream.ReadToEnd();

        // Convert it back to a Dictionary<int, DictionaryCheckup> object and store
        // it in our "H" variable
        H = JsonConvert.DeserializeObject<Dictionary<int, DictionaryCheckup>>(json);
    }
}

The above code reads/writes files that look like this:

{
  "180000": {
    "theGrouping": "H"
  },
  "180001": {
    "theGrouping": "H"
  },
  "180303": {
    "theGrouping": "H"
  }
}

Note that the above example is just for writing and loading a single dictionary. If you wanted, you could change the code to store an array of dictionaries (or even dictionaries of dictionaries) which would then allow adding or removing dictionaries via copy-paste.

AtinSkrita
  • 1,373
  • 12
  • 13