Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well, here's your original code made generic:</p> <pre><code>public static List&lt;T&gt; SortResults&lt;T&gt;(List&lt;T&gt; listRow, string sortColumn, bool ascending) { switch (ascending) { case true: return (from r in listRow orderby r.GetType().GetField(sortColumn).GetValue(r) select r).ToList(); case false: return (from r in listRow orderby r.GetType().GetField(sortColumn).GetValue(r) descending select r).ToList(); default: return listRow; } } </code></pre> <p>Note how I've removed the type argument from the <code>ToList</code> calls - let the compiler work it out :)</p> <p>(As an aside, I don't know why the compiler requires a <code>default</code> case here. Maybe it just always assumes there will be unlisted potential values.)</p> <p>However, this can be made nicer:</p> <pre><code>public static List&lt;T&gt; SortResults&lt;T&gt;(List&lt;T&gt; listRow, string sortColumn, bool ascending) { FieldInfo field = typeof(T).GetField(sortColumn); Func&lt;T, object&gt; projection = t =&gt; field.GetValue(t); IEnumerable&lt;T&gt; sequence = ascending ? listRow.OrderBy(projection) : listRow.OrderByDescending(projection); return sequence.ToList(); } </code></pre> <p>This is still fairly inefficient (as it's using reflection) but at least it's not getting the <code>FieldInfo</code> separately for each item. If you want better performance, you can have a generic helper type which caches a delegate mapping a value to the field's value for each field, and then fetch that delegate once at the start of the method. It would definitely be more work, but I'd expect it to be an order of magnitude faster.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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