Home > Blockchain >  Returning objects from a class property to a dictionary
Returning objects from a class property to a dictionary

Time:01-17

I'm looking for a way to return properties in a class, back into a a dictionary. Let me give an example...

If you have a model like this:

public class MyModelTemplate
{
    string TestString { get; set; }
    bool TestBool { get; set; }
}

And give it some values in the setter:

public class TestClass
{
    public MyModelTemplate Model_one
    {
        get { return Model_one; }
        set { value.TestString = "I am a string"; value.TestBool = true; }
    }

    public MyModelTemplate Model_two
    {
        get { return Model_two; }
        set { value.TestString = "I am a string TWO"; value.TestBool = false; }
    }
}

Would it be possible to make a function and put the items in a Dictionary?

  public static Dictionary<string, object> GetValuesFromModel(object model)
    {
        // Return the object from the model in a dictionary
        return strReturnValues;
    }

CodePudding user response:

The properties in MyModelTemplate must be public.

You got it wrong with TestClass. Try this

public class TestClass
{
    // Constructor
    public TestClass ()
    {
        Model_one = new MyModelTemplate{ 
            TestString = "I am a string", TestBool = true };
        Model_two = new MyModelTemplate{ 
            TestString = "I am a string TWO", TestBool = false };
    }

    public MyModelTemplate Model_one { get; set; }

    public MyModelTemplate Model_two { get; set; }
}

A solution with a dictionary instead of properties:

public class TestClass
{
    public Dictionary<string, MyModelTemplate> Models { get; } =
        new Dictionary<string, MyModelTemplate>();

    public TestClass()
    {
        Models.Add("Model_one", new MyModelTemplate{ 
            TestString = "I am a string", TestBool = true });
        Models.Add("Model_two", new MyModelTemplate{
            TestString = "I am a string TWO", TestBool = false });
    }
}

Now, you can access the dictionary like this

var test = new TestClass();
var model = test["Model_one"];
Console.WriteLine(model.TestString);
Console.WriteLine(model.TestBool);

CodePudding user response:

You can use Reflection in such cases. Please have a look on the code below -

public static void Main()
{
    var model1 = new MyModelTemplate() {TestString="A", TestBool = true};
    foreach(var pair in GetValuesFromModel(model1)){
        Console.WriteLine($"{pair.Key} - {pair.Value}");
    }
}

public static Dictionary<string, object> GetValuesFromModel(object model)
{
    var result = new Dictionary<string, object>();
    var props = model.GetType().GetProperties();
    foreach(var prop in props){
        result.Add(prop.Name, (object)prop.GetValue(model));
    }
    return result;
}

It should give you following output on console -

TestString - A
TestBool - True
  •  Tags:  
  • Related