3

If the SQL query I use to populate a generic List orders the result set like so (List<InventoryItem> inventoryItems is populated):

SELECT id, pack_size, description, department+(subdepartment/100) AS Dept, vendor_id, vendor_item, ave_cost, unit_list FROM t_inv ORDER BY id, pack_size

...is it redundant (it seems to me that it is, but I want to verify it) to use .OrderBy().ThenBy() in subsequent LINQ code like this:

public IEnumerable<InventoryItem> Get(string ID, int packSize, int CountToFetch)
{
    return inventoryItems
        .Where(i => (i.Id.CompareTo(ID) == 0 && i.PackSize > packSize) || i.Id.CompareTo(ID) > 0)
        .OrderBy(i => i.Id)
        .ThenBy(i => i.PackSize)
        .Take(CountToFetch);
}

?

I probably could afford the miniscule amount of additional Purina Gerbil Chow required to power this, but (call me a PETA pet if you will) I'd still rather not waste energy needlessly.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

4

If you are sorting the data at your database there is no need to sort it again

iamkrillin
  • 6,798
  • 1
  • 24
  • 51
4

Since the SQL query that serves as the source of your LINQ query is part of your code, and because you know for sure that the records are going to be ordered, there is no point to enforce the ordering in your LINQ as well. If anything, add a debug assertion to check that the data is coming in correctly sorted, and turn off debug assertions in production.

The philosophy behind it is that you should have only one piece of code responsible for each piece of functionality. If someone modifies your query to bring items out of order, in all likelihood he does not understand what you were doing. It is better to point that out right away by an assertion, than to mask it with "belt and suspenders" sort in the LINQ part of your code.

It goes without saying that decisions like this one need to be well documented: you need to add a comment explaining that your function expects its input data to be sorted in a particular way, and that feeding unsorted data is an error.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523