That guy
That guy

Reputation: 133

C# Adding an array of dynamic objects into a List of dynamic objects

So i have an object of ojects like so

    [["value1","value2","value3"]]

and my goal is to access these objects, and modify them, then return it to a new list containing the existing objects.

Here's what I've tried

    List<dynamic> data = new List<dynamic>();
    foreach(var i in objects)
    {
       List<dynamic> innerData = new List<dynamic>();
       foreach(var j in i)
       {
           innerData.Add(j + " NEW");
       }
       data.AddRange(innerData);
    }

the output isn't the same. It will return the following

    [["value1 NEW"], ["value2 NEW"],["value3 NEW"]]

It returns a new list, but instead of having one object with three values inside the list, it returns three objects with one value inside the list.

My goal is to have the same output format as the input format. Like so

    [["value1 NEW","value2 NEW", "value3 NEW"]]

Upvotes: 0

Views: 3428

Answers (1)

Aleš Doganoc
Aleš Doganoc

Reputation: 12052

As already suggested in the comments you need to use Add instead of AddRange. AddRange adds each element of a list as a new element in the outer list and what you want is add the inner list as one element of the outer list.

The fixed code then looks like this:

List<dynamic> data = new List<dynamic>();
foreach(var i in objects)
{
    List<dynamic> innerData = new List<dynamic>();
    foreach(var j in i)
    {
        innerData.Add(j + " NEW");
    }
    data.Add(innerData);
}

Upvotes: 1

Related Questions