Why the order of LINQ to objects methods counts

前端 未结 5 2104
一整个雨季
一整个雨季 2021-02-14 15:58

I read this question\'s answers that explain the order of the LINQ to objects methods makes a difference. My question is why?

If I write a LINQ to SQL query, it doesn\'t

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-14 16:45

    Linq to objects's deferred execution works differently than linq-to-sql's (and EF's).

    With linq-to-objects, the method chain will be executed in the order that the methods are listed—it doesn't use expression trees to store and translate the whole thing.

    Calling OrderBy then Where with linq-to-objects will, when you enumerate the results, sort the collection, then filter it. Conversely, filtering results with a call to Where before sorting it with OrderBy will, when you enumerate, first filter, then sort. As a result the latter case can make a massive difference, since you'd potentially be sorting many fewer items.

提交回复
热议问题