c# - Creating N objects and adding them to a list -
i have method takes in n, number of objects want create, , need return list of n objects.
currently can simple loop:
private static ienumerable<myobj> create(int count, string foo) { var mylist = new list<myobj>(); (var = 0; < count; i++) { mylist .add(new myobj { bar = foo }); } return mylist; }
and i'm wondering if there way, maybe linq create list.
i've tried:
private static ienumerable<myobj> createpaxpricetypes(int count, string foo) { var mylist = new list<myobj>(count); return mylist.select(x => x = new myobj { bar = foo }); }
but seem populate list.
i tried changing select foreach same deal.
i realized list has capacity of count , linq not finding elements iterate.
mylist.foreach(x => x = new myobj { bar = foo });
is there correct linq operator use work? or should stick loop?
you can use range
create sequence:
return enumerable.range(0, count).select(x => new myobj { bar = foo });
if want create list
, you'd have tolist
it.
mind though, it's (arguably) non-obvious solution, don't throw out iterative way of creating list yet.
Comments
Post a Comment