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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -