How Can I dynamically create objects in C# Type and Name

226 views Asked by At

enter image description here

I want to create a list of dynamically created objects.

Then I want to add this object to a list.

So in the Above example I would like to create a list of type entity with a name of Image

        List<DataConsistencyModel> dataConsistencyModels = new List<DataConsistencyModel>
        {
              new DataConsistencyModel{   PropertyName = "Logo",TypeOf = typeof (Entity),ValidFunction =  x => x.GroupId == null},                      
        };

        foreach (DataConsistencyModel dcm in dataConsistencyModels)
        {

            List<TypeOf> PropertyName = Data.Where(dcm.ValidFunction).ToList();

        }   
1

There are 1 answers

0
Parsa Gachkar On

Using a List of Dictionaries would be a useful workaround!

        var myObject = new List<Dictionary<string,object>>
        {
            new Dictionary<string, object>
            {
                {"val1", 1},
                {"val2", true},
                {"val3", "String1"}
            },
            new Dictionary<string, object>
            {
                {"val1", 2},
                {"val2", true},
                {"val3", "String2"}
            }
        };
        // you can add as many Values as you want
        myObject.Add(new Dictionary<string, object>
        {
            {"val1", 2},
            {"val2", true},
            {"val3", "my new String"},
            {"val4", "my new String 2"}
        });
        // Use Keys to access values (Don't Forget casting)
        var output = (String) myObject[0]["val3"];