How can i insert a new object to 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’s limit(size).
I convert it to List. To insert a new object.
v.ToList().Add(new { Name = "c", Surname = "d", Age = 3 });
But still i have 2 elements in v variable. Where has the third element gone?
But i can’t assign to another List variable.
List newV = v.ToList();
.ToList()produces a new list object, adding all the elements of the input source, your array, into it. As such, the original array isn’t changed at all.You cannot add elements to an existing array, it has a fixed size, the only thing you can do is put a new array back into the variable.
I haven’t tried it, but try this:
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 just creating a named type, and using a list to begin with.
Note that you cannot write
List l = v.ToList();as the type of the list is generic (it will return someList<some-anonymous-type-here>, not justList. With anonymous types, you need to usevar.