Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This actually turned out to be a GIANT headache to try to solve; but in the end, it actually turned out being very easy to accomplish with a bit of hackishness and reflection:</p> <pre><code>public class Program { public class SomeClass { public int Id { get; set; } public string Name { get; set; } } static void Main(string[] args) { List&lt;SomeClass&gt; sample = new List&lt;SomeClass&gt; { new SomeClass { Id = 4, Name = "ABC" }, new SomeClass { Id = 1, Name = "XYZ" }, new SomeClass { Id = 2, Name = "JKL" } }; var result = sample.OrderByDynamic("Name", OrderDirection.Ascending).ToList(); result.ForEach(x =&gt; Console.WriteLine("Id: " + x.Id + " | Name: " + x.Name)); Console.ReadKey(); } } public enum OrderDirection { Ascending, Descending } public static class LinqExtensions { public static IEnumerable&lt;T&gt; OrderByDynamic&lt;T&gt;(this IEnumerable&lt;T&gt; source, string propertyName, OrderDirection direction = OrderDirection.Ascending) { if(direction == OrderDirection.Ascending) return source.OrderBy(x =&gt; x.GetType().GetProperty(propertyName).GetValue(x, null)); else return source.OrderByDescending(x =&gt; x.GetType().GetProperty(propertyName).GetValue(x, null)); } } </code></pre> <p>This example worked for me in test situations; I could supply the property name, and specify a sort direction, and it worked great. Simply call like so:</p> <pre><code>yourEnumerable.OrderByDynamic("YourPropertyName"); yourEnumerable.OrderByDynamic("YourPropertyName", OrderDirection.Descending); </code></pre> <p>Enjoy!</p>
 

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