1

Suppose these two codes:

1) using foreach with Add in new list

var myList = new List<MyType>();
foreach(var myType in otherEntity.ListOfMyType) {
    myList.Add(new MyType {
        //... copy properties here
    });
}

2) using select

var myList = otherEntity.ListOfMyType.Select(myType => new MyType {
    //... copy properties here
});

Exists other advantages on use select instead foreach beyond readability?

Gean Ribeiro
  • 1,025
  • 2
  • 10
  • 23
  • In your case there is little difference between the two pieces of code. There may be some very minor performance differences (minor enough that I doubt you'd notice). So yeah, its just down to readability here I think. – Chris Mar 03 '17 at 17:44
  • 1
    Possible duplicate of [this](http://stackoverflow.com/questions/5322586/c-sharp-performance-of-linq-vs-foreach-iterator-block)... and [this](http://stackoverflow.com/questions/22851234/linq-vs-foreach-vs-for-performance-test-results)... and [this](http://stackoverflow.com/questions/3156059/is-a-linq-statement-faster-than-a-foreach-loop) – Josh Part Mar 03 '17 at 17:45
  • 6
    `Select` is lazy and returns a more general type (`IEnumerable` instead of `List`) which could be an advantage. – Lee Mar 03 '17 at 17:45
  • @Lee: I have to admit given the name of the variable I just assumed there was going to be a ToList() call on the end that got left off. I probably should have checked that though. :) – Chris Mar 03 '17 at 17:56

1 Answers1

2

The major difference between these two pieces of code is deferred execution:

  • In the first case, you have a List<MyType> which is fully "materialized" in memory
  • In the second case, you have an IEnumerable<MyType>, which is not taking any memory

If you decide to enumerate myList to the middle, the second solution would construct as many entries as needed, while the first construct creates every MyType object ahead of time.

On the other hand, having a list make multiple enumerations potentially more expensive in terms of CPU cycles.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523