Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I specify LINQ's OrderBy direction as a boolean?
    primarykey
    data
    text
    <p>I have a simple data class that has this signature:</p> <pre><code>internal interface IMyClass { string Letter { get; } int Number { get; } } </code></pre> <p>I wish to be able to sort this data based on a field (specified as <code>string sortField</code>) and a direction (specified as <code>bool isAscending</code>)</p> <p>Currently I am using a <code>switch</code> (with the ascending logic within each case as <code>if</code>)</p> <pre><code>IEnumerable&lt;IMyClass&gt; lst = new IMyClass[];//provided as paramater switch (sortField) { case "letter": if( isAscending ) { lst = lst.OrderBy( s =&gt; s.Letter ); } else { lst = lst.OrderByDescending( s =&gt; s.Letter ); } break; case "number": if( isAscending ) { lst = lst.OrderBy( s =&gt; s.Number ); } else { lst = lst.OrderByDescending( s =&gt; s.Number ); } break; } </code></pre> <p>This is pretty ugly, for 2 properties, but when the sort logic differs it becomes a problem (we also see <code>s =&gt; s.Number</code> is duplicated twice in the code)</p> <p><strong>Question</strong> What is the best way to pass a boolean to choose the sort direction?</p> <p><strong>What I've Tried</strong> I've ripped apart System.Core.dll and found the OrderBy Extension method implementations:</p> <p>OrderBy:</p> <pre><code>public static IOrderedEnumerable&lt;TSource&gt; OrderBy&lt;TSource, TKey&gt;( this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector ){ return new OrderedEnumerable&lt;TSource, TKey&gt;( source, keySelector, null, false ); } </code></pre> <p>OrderByDescending:</p> <pre><code>public static IOrderedEnumerable&lt;TSource&gt; OrderByDescending&lt;TSource, TKey&gt;( this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector ){ return new OrderedEnumerable&lt;TSource, TKey&gt;( source, keySelector, null, true ); } </code></pre> <p>It appears the purpose of having 2 named methods is to abstract this boolean away. I can't create my own extension easily as <code>OrderedEnumberable</code> is internal to System.Core, and writing a layer to go from bool -> methodName -> bool seems wrong to me.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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