I have the following code:
IQueryable<Guid> GetOrdered(IQueryable<Guid> ids)
{
return from id in ids join storedId in storedIds on id equals storedId.Id
orderby storedId.Something select id;
}
Now I want to introduce a parameter to GetOrdered()
and optionally change orderby
with orderby descending
. Something like this:
IQueryable<Guid> GetOrdered(IQueryable<Guid> ids, bool descending)
{
// how do I insert descending into the query below?
return from id in ids join storedId in storedIds on id equals storedId.Id
orderby storedId.Something select id;
}
Of course I could write two identical queries - one with orderby
and another with orderby descending
but that means code duplication.
Alternatively I could use a sub-statement for an unordered set and then conditionally order it like in this answer but the problem is I then need to Select()
a specific column and that latter Select()
will render an unordered result.
So I could try to craft a "smart" ordering condition as in this answer:
var result = from w in widgets where w.Name.Contains("xyz")
orderby
flag ? w.Id : 0,
flag ? 0 : w.Id descending
select w;
but the problem is I will often have a non-numeric column as one by which I need my set ordered.
How do I conditionally reverse the sorting order under these conditions?
select
after anorderby
, theselect
doesn't change the order of the results. (Although I could be wrong, maybe LINQ-to-objects provides more of a guarantee here than LINQ-to-SQL does.) – Rawling Jun 3 '13 at 11:20