2

I have a List<> that I've previously sorted by one of the fields on the object. If I perform a Where() on the list, am I safe to assume that the results of the Where will also be sorted?

// Sorted by salary, greatest to smallest.
List<Players> players = _playerRepo.GetAll().OrderByDescending(x => x.Salary).ToList();

// Is this list safe to assume that the players with smith as last name are sorted by salary as well?
List<Players> filteredPlayers = players.Where(x => x.LastName == "Smith").ToList();
Athari
  • 33,702
  • 16
  • 105
  • 146
Darthg8r
  • 12,377
  • 15
  • 63
  • 100
  • 1
    Yes. But you probably should have a get by last name method instead of pulling everything into memory and then filtering. – drneel Sep 10 '14 at 12:29
  • 2
    possible duplicate of [Preserving order with LINQ](http://stackoverflow.com/questions/204505/preserving-order-with-linq) – Cᴏʀʏ Sep 10 '14 at 12:30
  • 1
    The question is why you'are always creating lists. I would do the `ToList` only once at the end to safe memory and cpu cycles. – Tim Schmelter Sep 10 '14 at 12:31
  • Guys, it's just a contrived example to explicitly ask the question. – Darthg8r Sep 10 '14 at 13:05

2 Answers2

3

Yes. LINQ queries, in general, keep the order of elements.

Hint: don't call ToList if you want to filter the result further. You should peform query on the database, not on the client, if possible.

Athari
  • 33,702
  • 16
  • 105
  • 146
  • If you use the ToList() it execute's the query immediately. If not used it executes later, at the point when u need the information from the query. (some additional information on the previous comment) – Revils Sep 10 '14 at 12:35
2

Yes, Where will not change the order of a previously ordered list, it will only filter it.

Also, the ordering operations are stable, so equal values will stay in their original order.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194