Search code examples
c#toml

How do i convert a toml [Table] to a dictionary in C#?


I would like to read/convert a table form a Toml file into a dictionary<Tkey, Tvalue>. Here is an example for the Toml Table:

    [Parameters]
    param1 = [1,2,3,4,5]
    param2 = ["a","b","c","d"]

I'm using Tomlyn as the TOML parser. I can add link if it's allowed.

The problem i have is to parse my table "Parameters" to a dictionary. What am i doing wrong?

Here is my attempt:

```

using System;
using System.Collections.Generic;
using Tomlyn;
using Tomlyn.Model;

void main {
static void Main(string[] args) {


var toml = File.ReadAllText("parameters.toml");

TomlTable model = Toml.ToModel(toml);

// This is what i can't figure out to do correctly
Dictionary<string, object> databaseDictionary = model["Parameters"].ToDictionary();

// Print the contents of the dictionary
foreach (KeyValuePair<string, object> pair in databaseDictionary)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}
}

```

Thx Mike/


Solution

  • Your problem is that Tomltable doesn't have the Todictionary() method. You need to make a workaround.

    You can use Dictionary<TomlKey, TomlObject> to initialize a dictionary first instead of model["Parameters"].ToDictionary();, then start iterating over your table and inserting its values into the dictionary. as follows:

    class Program
    {
        static void Main(string[] args)
        {
            var toml = File.ReadAllText("parameters.toml");
            
            TomlTable table = Toml.Parse(toml);
            TomlTable parameters = table.Get<TomlTable>("Parameters");
    
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
    
            foreach (var kvp in parameters)
            {
                string key = kvp.Key.ToString();
                object value = kvp.Value.ToObject();
    
                dictionary.Add(key, value);
            }
    
            // Print the contents of the dictionary
            foreach (var pair in dictionary)
            {
                Console.WriteLine($"{pair.Key}: {pair.Value}");
            }
        }
    }