c# - How to create a List of Anonymous types? -
i trying create list of anonymous types shown below making mistake somewhere
for (int = 0; < 10; i++) { var list = new[] { new { number = i, name = string.concat("name",i) } }; }
e.g.
var o1 = new { id = 1, name = "name1" }; var o2 = new { id = 2, name = "name2" }; var list = new[] { o1, o2 }.tolist();
how same @ runtime?
help needed.
no error...but collection 1
that because creating new list in each iteration
you can try like:
var list = new[] { new { number = 0, name = "name1" } }.tolist(); //just create //list of anonymous type object list.clear(); (int = 0; < 10; i++) { list.add(new { number = i, name = string.concat("name",i) }); }
or 1 way use list<object>
like:
list<object> list = new list<object>(); (int = 0; < 10; i++) { list.add(new { number = i, name = string.concat("name",i) }); }
or can use enumerable.range like
var list = enumerable.range(0, 10) .select(i => new { number = i, name = "somename" }) .tolist();
Comments
Post a Comment