c# - Should I use a simple foreach or Linq when collecting data out of a collection -


for simple case, class foo has member i, , have collection of foos, ienumerable<foo> foos, , want end collection of foo's member i, list<typeofi> result.

question: preferable use foreach (option 1 below) or form of linq (option 2 below) or other method. or, perhaps, it not worth concerning myself (just choose personal preference).

option 1:

foreach (foo foo in foos)     result.add(foo.i); 

option 2:

result.addrange(foos.select(foo => foo.i)); 

to me, option 2 looks cleaner, i'm wondering if linq heavy handed can achieved such simple foreach loop.

looking opinions , suggestions.

i prefer second option on first. however, unless there reason pre-create list<t> , use addrange, avoid it. personally, use:

 list<typeofi> results = foos.select(f => f.i).tolist(); 

in addition, not use tolist() unless need true list<t>, or need force execution immediate instead of deferred. if need collection of "i" values iterate, use:

 var results = foos.select(f => f.i); 

Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -