0

I need to convert Dictionary to object that contain enum but I got error error : cant cast enum and i cant fix it

private static T DictionaryToObject<T>(IDictionary<string, string> dict) where T : new()
{
    var t = new T();
    PropertyInfo[] properties = t.GetType().GetProperties();
 
    foreach (PropertyInfo property in properties)
    {
        if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
            continue;
 
        KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
 
        // Find which property type (int, string, double? etc) the CURRENT property is...
        Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
 
        // Fix nullables...
        Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
 
        // ...and change the type
        object newA = Convert.ChangeType(item.Value, newT);
        t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
    }
    return t;
}
  • 1
    You'll need to provide example objects and inputs to the method for us to know what about your inputs is incorrect. Also it rather defeats the purpose of using a dictionary if you're just going to iterate through all key value pairs every time you try to find something by key. You should be using the methods specifically designed to search by key (in this case TryGetValue) to take advantage of the data structure that you have. Otherwise just accept a list or IEnumerable if you're just going to do nothing but iterate though it anyway. – Servy Dec 04 '21 at 00:39
  • Are you looking for ExpandoObject functionality? https://stackoverflow.com/questions/4938397/dynamically-adding-properties-to-an-expandoobject I agree with Servy, it sounds like you're fighting against the data type you're using. – gunr2171 Dec 04 '21 at 00:40

1 Answers1

1

I think you can convert a dictionary to a typed object by using a simpler way: a Newtonsoft.Json NuGet package.

namespace MappingTest
{
  using System;
  using System.Collections.Generic;
  using Newtonsoft.Json.Linq;

  class Program
  {
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, string>
        {
            {"TestProp1", "TestValue1"},
            {"TestProp2", "TestValue2"}
        };

        var myClass = DictionaryToObject<MyClass>(dict);

        Console.WriteLine($"myClass.TestProp1: {myClass.TestProp1}");
        Console.WriteLine($"myClass.TestProp2: {myClass.TestProp2}");
    }

    enum TestValues
    {
        TestValue1,
        TestValue2
    }

    class MyClass
    {
        public TestValues? TestProp1 { get; set; }
        public TestValues TestProp2 { get; set; }
    }

    private static T DictionaryToObject<T>(IDictionary<string, string> dict)
    {
        JObject obj = JObject.FromObject(dict);
        return obj.ToObject<T>();
    }
  }
}
Yevhen Cherkes
  • 626
  • 7
  • 10