locked
ExpandoObject One key with multiple values RRS feed

  • Question

  • User-2132497554 posted

    Hi folks,

    Here is my sample Code:

    var records = new List<dynamic>();
    dynamic record = new ExpandoObject() ;
    
    for (int i = 0; i < 5; i++)
    {
       record.Name = i;
       records.Add(record);
    }

    I am getting output Like:

    4
    4
    4
    4
    4

    But I want output like this:

    0
    1
    2
    3
    4

    Any Idea?
    Thanks



    Monday, May 10, 2021 8:39 AM

Answers

  • User475983607 posted

    Basically, the record variable is a reference type pointing to a memory location.  When the loop completes the generic type, records, contains four pointers to the same memory location which has a 4.

    The basic problem you are facing is not understanding how the ExpandoObject works.  The following will work but I'm not sure if this is will work in your application.

                var records = new List<dynamic>();
                dynamic record;
    
                for (int i = 0; i < 5; i++)
                {
                    record = new ExpandoObject();
                    record.Name = i;
                    records.Add(record);
                }
    
                foreach(var item in records)
                {
                    Console.WriteLine(item.Name);
                }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 10, 2021 11:35 AM

All replies

  • User475983607 posted

    Basically, the record variable is a reference type pointing to a memory location.  When the loop completes the generic type, records, contains four pointers to the same memory location which has a 4.

    The basic problem you are facing is not understanding how the ExpandoObject works.  The following will work but I'm not sure if this is will work in your application.

                var records = new List<dynamic>();
                dynamic record;
    
                for (int i = 0; i < 5; i++)
                {
                    record = new ExpandoObject();
                    record.Name = i;
                    records.Add(record);
                }
    
                foreach(var item in records)
                {
                    Console.WriteLine(item.Name);
                }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 10, 2021 11:35 AM
  • User753101303 posted

    Hi,

    Or if you prefer, you create an objet and then you update and add the same object again and again inside your loop. A a result you end up with a list that this storing the SAME object multiple times.

    Instead and as suggested already, you likely want to create a new object INSIDE your loop that you can then update and add resulting in a list that will hold distinct objects.

    Monday, May 10, 2021 12:05 PM