0

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"]]
11
  • Can't you just add them straight to the data list in your inner loop? Instead of adding them to a second list, and adding the list to the full list. Commented Oct 15, 2019 at 20:56
  • The format will not be the same. It will add multiple each of them independently. My goal is to add the entire group, containing the independent values Commented Oct 15, 2019 at 21:03
  • You did an AddRange. Try doing Add. I'm not sure if the compiler will allow that but what you did was basically add each item in the internal collection to the main collection. And what you want is add it as a collection. Commented Oct 15, 2019 at 21:06
  • 1
    @Thatguy use Add instead of AddRange. Commented Oct 15, 2019 at 21:11
  • 1
    As @iSR5 said; if you want the double-square brackets then Add will achieve that Commented Oct 15, 2019 at 21:14

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.