Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can try custom <code>IComparer</code>:</p> <pre><code>public class MyComparer&lt;T&gt; : IComparer&lt;T&gt; { public MyComparer(bool ascending){ Descending = !ascending; } public bool Descending {get;set;} public int Compare(T x, T y){ //your normal logic int result = ....; return Descending ? -result : result; } } </code></pre> <p>Then use it in your <code>OrderBy</code> query:</p> <pre><code>source.OrderBy(o=&gt;o.MyColumnToOrderBy, new MyComparer(true));//true for ascending and false for descending </code></pre> <h2>UPDATE</h2> <p>You can use some <code>enum</code> instead of <code>bool</code> to indicate the sorting direction:</p> <pre><code>public class MyComparer&lt;T&gt; : IComparer&lt;T&gt; { public MyComparer(SortingDirection sortDir){ Direction = sortDir; } public SortingDirection Direction {get;set;} public int Compare(T x, T y){ //your normal logic int result = ....; return Direction == SortingDirection.Descending ? -result : result; } public enum SortingDirection { Ascending, Descending } } //o.SortingDirection should be type of enum SortingDirection source.OrderBy(o=&gt;o.MyColumnToOrderBy, new MyComparer(o.SortingDirection)); </code></pre> <p><strong>Another work-around</strong></p> <p>I think you can use a little trick with <code>GroupBy</code> to order by <code>o.SortingDirection</code>, like this:</p> <pre><code>source.GroupBy(x=&gt;x.MyColumnToOrderBy) .SelectMany(g=&gt; o.SortingDirection == SortingDirection.Ascending ? g.OrderBy(a=&gt;a.Key) : g.OrderByDescending(a=&gt;a.Key)); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload