When I use a LINQ Where clause, does the returned list of items honor the order they were in the original list?
A single query expression may have multiple where clauses.
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.
In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With