Search code examples
c#arraysexpandoobject

Add new [] values to ExpandoObject


I want to add all values from myArr to myObj.

int[,] myArr = {
    {1, 2},
    {3, 4}
};

dynamic myObj = new ExpandoObject();

foreach(var myInt in myArr)
{
    myObj.Ints = new[]
    {
        new
        {
            value = myInt,
            value_plus_1 = myInt + 1
        }
    };
}

At the end of the foreach loop, I would like to have an object like this:

Ints: [
  {
    value: 1,
    value_plus_1: 2
  },
  {
    value: 2,
    value_plus_1: 3
  },
  {
    value: 3,
    value_plus_1: 4
  },
  {
    value: 4,
    value_plus_1: 5
  }
]

But every iteration I overwrite the value from the previous iteration, so at the end, I have something like this:

Ints: [
{
  {
    value: 4,
    value_plus_1: 5
  }
]

What do I need to change?


Solution

  • For every iteration of the loop, myObj.Ints is re-set with a new array value.

    Instead, you have to add each object to the array via index.

    dynamic myObj = new ExpandoObject();
    myObj.Ints = new dynamic[myArr.Length];
            
    int index = 0;
    foreach(var myInt in myArr)
    {
        myObj.Ints[index] = 
            new
            {
                value = myInt,
                value_plus_1 = myInt + 1
            };
                           
        index++;
    }
    

    Sample program


    Another way to do is with adding the object into List via System.Linq. Then assign the list to myObj.Ints.

    using System.Linq;
    
    dynamic myObj = new ExpandoObject();
    var list = new List<dynamic>();
            
    foreach(var myInt in myArr)
    {
        list.Add( 
            new
            {
                value = myInt,
                value_plus_1 = myInt + 1
            }
        );
    }
            
    myObj.Ints = list;
    

    Sample program 2