Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ Where clause honor order?

When I use a LINQ Where clause, does the returned list of items honor the order they were in the original list?

like image 400
daniely Avatar asked Mar 28 '12 15:03

daniely


People also ask

Can we use multiple where clause in LINQ?

A single query expression may have multiple where clauses.

What is default order by in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order.

Why LINQ query starts with from clause?

In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).

How does LINQ select work?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.


2 Answers

It depends on how the collection being queried has its GetEnumerator is implemented. If GetEnumerator iterates through the collection in the order added, then it will honor order.

UPDATE:

Here's an example that I put together with LINQPad:

var items = new List<int>() { 1,2,3,4,5 };
items.Insert(3, 100);

(from i in items
 where i > 2
 select i).Dump();

RESULT:

3 
100
4
5

So, the Where clause honors the order of the items in the list since List's GetEnumerator starts at the first item in the list and proceeds through the end.

like image 161
David Hoerster Avatar answered Sep 18 '22 01:09

David Hoerster


Where processes items in the order IEnumerable<T> gives. If you query an implementation of IEnumerable<T> thats keeps the order in which they are inserted (such as List<T>), then you keep the order. If you query a HashTable<T> for example, order is not guaranteed.

like image 41
Ortiga Avatar answered Sep 20 '22 01:09

Ortiga