Order of Where Clause Matters in Linq To Objects.

The order in which you apply where and join in SQL server does not matter too much. One of the reason is that SQL server has its own optimizer built in which knows how to rewrite the query so it is optimized for best performance. However we don' get that luxury with Linq to objects. Therefore it is essential that you understand how to write your query so that it gives you maximum efficiency. For instance apply your filter before joining because filtering would reduce the number of rows returned and as a result there would be fewer rows that you would need to join against. Here is a simple example that illustrates the performance gain that you would get when you apply the where clause before the join statement.

image

image

Above code took 2.5 sec to execute but when I rewrite my query so that my where clause comes before the join it takes less than 1 sec for the entire query to execute.

image

image

2 Comments

  • This is indeed one of the problems of LINQ. Where MS has tried to give us one interface for quering all sorts of data, the behaviour of the different implementations can be completely different (Which isn't weird at all imao), but most people who will start using LINQ will not know that and will have no clue what the cause of their problem is.

    LINQ is great, but not as easy as MS tries to let you think.

  • Great input!

Comments have been disabled for this content.