tags:

views:

73

answers:

2

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();
+4  A: 

.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:

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 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 some List<some-anonymous-type-here>, not just List. With anonymous types, you need to use var.

Lasse V. Karlsen
+1  A: 

It is not a "List" but a generic list typed on your anonymous type. Because of this, you will not be able to write out the type explicitly for this operation. You must either use "var newV = v.ToList()" or type it as an IEnumerable, which is a non-generic interface that generic lists implement.

Your above code for adding a new item might not be doing what you think, either. Right now it is not adding a new item to v, but creating a new list, adding an item to that list, and then the list is gone because you have no reference to it. You need to convert v to a list, then add the item.

Chris