Nett icon indicating copy to clipboard operation
Nett copied to clipboard

Save/Load Dictionary<ENUM, string>

Open PhilippPaetzold opened this issue 4 years ago • 1 comments

Hi all,

how is it possible to save and restore a dictionary with an enumeration type key and a string value?

I already tried to create custom settings and register a custom conversion with ConfigureType. Can somebody help me out?

Thanks in advance Philipp

PhilippPaetzold avatar May 22 '20 15:05 PhilippPaetzold

public enum TheEnum
{
    A, 
    B,
}

public class Foo
{
    public Dictionary<TheEnum, string> D { get; set; } = new Dictionary<TheEnum, string>();
}

[Fact]
public void Foooxy()
{
    var foo = new Foo();
    foo.D.Add(TheEnum.A, "a");
    foo.D.Add(TheEnum.B, "b");

    var conf = TomlSettings.Create(cfg => cfg
        .ConfigureType<Dictionary<TheEnum, string>>(tc => tc
            .WithConversionFor<TomlTable>(conv =>
                conv.FromToml(ConvertFromToml)
                .ToToml(ConvertToToml))));

    var w = Toml.WriteString(foo, conf);
    var r = Toml.ReadString<Foo>(w, conf);

    r.D[TheEnum.A].Should().Be("a");

    static Dictionary<TheEnum, string> ConvertFromToml(ITomlRoot root, TomlTable table)
    {
        var result = new Dictionary<TheEnum, string>();  
                
        foreach(var r in table.Rows)
        {
            var key = (TheEnum)Enum.Parse(typeof(TheEnum), r.Key);
            result.Add(key, r.Value.Get<string>());
        }

        return result;
    }

    static void ConvertToToml(Dictionary<TheEnum, string> d, TomlTable t)
    {
        foreach(var kvp in d)
        {
            t.Add(kvp.Key.ToString(), kvp.Value);
        }
    }
}

paiden avatar May 23 '20 07:05 paiden