-3

I have a dictionary and I need to change the dictionary on c# model.How to do it?

var number = new Dictionary<string, int>
    {
        {"One", 1},
        {"Two", 2},  
        {"Three", 3}

   };

Model:

public class Number
{
    public double One{ get; set; }
    public double Two { get; set; }
    public double Three { get; set; }

}

2 Answers2

0

We can use Reflection to get the properties on the Model and update the same on the dictionary like below where obj is the model object

var propertyCollection = typeof(Number).GetProperties();
foreach (var item in propertyCollection)
{
    if (number.ContainsKey(item.Name.ToString()))
    {
        number[item.Name.ToString()] = Int32.Parse(item.GetValue(obj));
    }
}
Test12345
  • 1,625
  • 1
  • 12
  • 21
  • if the values in the dictionary are statically (they dont change), its better to use the key as an index because reflection is slow. – Jonas Sep 23 '19 at 08:15
0

If the objective is to change the dictionary to class, then you should change your class structure to below (key-value pair)

    public class Number
    {
        public string number { get; set; }
        public double value { get; set; }
        public Number(string number, double value)
        {
            this.number = number;
            this.value = value;
        }
    }

and inject the values to class by creating an object of list of number

    static void Main(String[] args)
    {
        List<Number> numbers = new List<Number>();
        numbers.Add(new Number("One", 1));
        numbers.Add(new Number("Two", 2));
        numbers.Add(new Number("Three", 3));
    }
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25