How can I insert a new object into an anonymous array?

How can I insert a new object into an anonymous array?

var v = new[] { new {Name = "a", Surname = "b", Age = 1}, new {Name = "b", Surname = "c", Age = 2} }; 

I know, first of all, we set the array limit (size).

I convert it to List. Insert a new object.

 v.ToList().Add(new { Name = "c", Surname = "d", Age = 3 }); 

But still I have 2 elements in the variable v. Where did the third element go?

But I cannot assign another List variable.

 List newV = v.ToList(); 
+4
source share
3 answers

.ToList() creates a new list object, adding to it all the elements of the input source, your array. Thus, the original array does not change at all.

You cannot add elements to an existing array, it has a fixed size, the only thing you can do is return the new array to a variable.

I have not tried, but I will try:

 var l = v.ToList(); l.Add(...); // your existing add code v = l.ToArray(); 

But note that at this point you should look at why you want to use anonymous types in the first place, I would seriously think about simply creating a named type and using a list to start with.

Note that you cannot write List l = v.ToList(); , since the type of the list is general (it will return multiple List<some-anonymous-type-here> , not just List ). With anonymous types, you need to use var .

+5
source

This is not a "List", but a general list typed by your anonymous type. Because of this, you cannot explicitly write out the type for this operation. You must either use "var newV = v.ToList ()" or enter it as IEnumerable, which is not a common interface that implements shared lists.

Your above code to add a new item may not do what you think. Now it does not add a new item to v, but creates a new list by adding an item to this list, and then the list leaves because you do not have a link to it. You need to convert v to list and then add item.

+1
source

In fact, you should be able to. For your anonymous array v, you can add a new element as follows:

 v[2] = new {Name = "c", Surname = "d", Age = 3}; 

After adding a new element, you can check it, for example, with the following line of code:

 MessageBox.Show(v[2].ToString()); 
-1
source

Source: https://habr.com/ru/post/1300290/


All Articles