-1

I have a class as shown below.

public class MyClass
{
    public DateTime Date
    { get; set;}

    public double Col1
    { get; set;}

    public double Col2
    { get; set;}

    public double Col3
    { get; set;}

And I have a list of values in the

Dictionary<string, double> Items 
Items["AA", 23.56] // these AA, BB values will change. 
Items["BB", 15.456] etc

and I want to set the value of properties of the MyClass. Is this possible as shown below:

MyClass obj = new MyClass();
int i = 0;

foreach (KeyValuePair<string, double> entry in items)
{
    // take the first property (Col1) and assign the value.
    obj[i] = entry.value;   // is this possible
    i++;
}

OR

Here I am iterating through the class properties using reflection and find each value from the Dictionary then assign it to the Myclass property.

MyClass obj = new MyClass();
PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach (PropertyInfo property in properties)
{
    var value = // take the value from Dictionary.
    property.SetValue(obj, value);
}

The aim of the question is to set the value of MyClass's properties at run time. I dont know how many items will be present in the Dictionary in advance. Finally it will be like,

       MyClass obj = new MyClass();
       obj.Col1 = 23.56 // value of AA
       obj.Col2 = 15.456 // value of BB
       obj.Col3 = 100.23 // value of CC...it goes like this.

Is this possible? If yes, how?

Jassim S
  • 23
  • 5
  • 1
    "_I want to create the object of the above class_" vs. "_So dynamically create a class with its properties_" Uh... which one is it now? Please **edit** your question and make it clear and unambiguous... –  Sep 30 '22 at 17:01
  • You can't create class dynamically. You can create object (instance of class) dynamically. – Alexander Petrov Sep 30 '22 at 17:07
  • 1
    Of course [classes/types can be created dynamically at runtime](https://stackoverflow.com/questions/3862226/how-to-dynamically-create-a-class). But it's something quite advanced, though... –  Sep 30 '22 at 17:11
  • but why are you setting the properties of the same object again and again? Do you want a list of object? – Vivek Nuna Sep 30 '22 at 17:28
  • @viveknuna bro it is inside a while loop. Each while will create the class object and set its properties at runtime. This is reading from a csv file and each csv file, the number of columns and name of the header column will be different. – Jassim S Oct 01 '22 at 15:39

2 Answers2

1

Finally I did it myself.

        while (csv.Read())
        {
            string d0 = csv.GetField<string>("DATETIME");
            double? d5 = csv.GetField<double?>("SECONDS");

            if (!string.IsNullOrEmpty(d0))
            {
                DateTime dt = DateTime.Parse(d0, CultureInfo.InvariantCulture).AddMilliseconds(d5.HasValue == true ? d5.Value : 0);                                   

                ModelData md = new ModelData();
                md.Date = dt;

                PropertyInfo[] properties = typeof(ModelData).GetProperties();                    

                foreach (string str in columns)
                {
                    var d1 = csv.GetField<double>(str);
                    foreach (PropertyInfo property in properties)
                    {
                        if(property.PropertyType == typeof(Double?))
                        {
                            if (property.GetValue(md) == null)
                            {
                                property.SetValue(md, d1);
                                break;
                            }
                        }                            
                    }
                }               
                lstValues.Add(md);
               
            }              
Jassim S
  • 23
  • 5
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 06 '22 at 00:33
0

You can try ExpandoObject like below. It might solve your problem.

dynamic expando = new ExpandoObject();
var expandoDict = expando as IDictionary<string, object>;

foreach (KeyValuePair<string, double> entry in items)
{

    if (expandoDict.ContainsKey(entry.Key))
        expandoDict[entry.Key] = entry.Value;
    else
        expandoDict.Add(entry.Key, entry.Value);
}

More details please click here

It Just Like a Class (See below)

enter image description here

Pradeep Kumar
  • 1,193
  • 1
  • 9
  • 21
  • Bro do u know how to iterate through expando class properties ?? something foreach(var d in expando)......??? thanks – Jassim S Oct 01 '22 at 14:56
  • you can convert it to dictionary as i did in answer and then iterate n keyvaluepair. if still it not resolve your problem then let me. – Pradeep Kumar Oct 01 '22 at 16:09
  • here is the code var expandoDict1 = expando as IDictionary; foreach (var key in expandoDict1.Keys) { var value = expandoDict1[key]; } – Pradeep Kumar Oct 01 '22 at 16:22