Should I use simple foreach or Linq when collecting data from a collection

For the simple case of class foohaving a member i, and I have a collection of foos, say IEnumerable<Foo> foos, and I want to get a collection of foo member i, say List<TypeOfi> result.

Question : it is preferable to use foreach (option 1 below) or some form of Linq (option 2 below) or some other method. Or maybe it’s not even worth it on my part (just select my personal preferences).

Option 1 :

foreach (Foo foo in foos)
    result.Add(foo.i);

Option 2 :

result.AddRange(foos.Select(foo => foo.i));

For me, option 2 looks cleaner, but I wonder if Linq is too heavy for something that can be achieved with such a simple foreach loop.

Look for all opinions and suggestions.

+3
4

. , List<T> AddRange, . :

 List<TypeOfi> results = foos.Select(f => f.i).ToList();

, ToList(), List<T>, , . "i" , :

 var results = foos.Select(f => f.i);
+6

. ( , ).

LINQ , , , , , "", .

, , :

var result = foos.Select(f => f.i).ToList();

result.

+3

LINQ , foreach, linq- , foreach .

, , linq . linq - , - , . , , , Where , , linq, , / .

+3

,

foos.Select(foo => foo.i).ToList<TypeOfi>();
0

Source: https://habr.com/ru/post/1794221/


All Articles