<p>I found an example in the <a href="http://msdn2.microsoft.com/en-us/bb330936.aspx" rel="noreferrer">VS2008 Examples</a> for Dynamic LINQ that allows you to use a SQL-like string (e.g. <code>OrderBy(&quot;Name, Age DESC&quot;))</code> for ordering. Unfortunately, the method included only works on <code>IQueryable&lt;T&gt;</code>. Is there any way to get this functionality on <code>IEnumerable&lt;T&gt;</code>?</p>

[{'answer_id': 41262, 'author': 'Kjetil Watnedal', 'author_id': 4116, 'author_profile': 'https://Stackoverflow.com/users/4116', 'pm_score': 6, 'selected': False, 'text': '<p>I guess it would work to use reflection to get whatever property you want to sort on:</p>\n\n<pre><code>IEnumerable&lt;T&gt; myEnumerables\nvar query=from enumerable in myenumerables\n          where some criteria\n          orderby GetPropertyValue(enumerable,"SomeProperty")\n          select enumerable\n\nprivate static object GetPropertyValue(object obj, string property)\n{\n    System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);\n    return propertyInfo.GetValue(obj, null);\n}\n</code></pre>\n\n<p>Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.</p>\n'}, {'answer_id': 41427, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 3, 'selected': False, 'text': '<p>You could add it:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; OrderBy( this IEnumerable&lt;T&gt; input, string queryString) {\n    //parse the string into property names\n    //Use reflection to get and sort by properties\n    //something like\n\n    foreach( string propname in queryString.Split(\',\'))\n        input.OrderBy( x =&gt; GetPropertyValue( x, propname ) );\n\n    // I used Kjetil Watnedal\'s reflection example\n}\n</code></pre>\n\n<p>The <code>GetPropertyValue</code> function is from <a href="https://stackoverflow.com/questions/41244/dynamic-linq-orderby#41262">Kjetil Watnedal\'s answer</a></p>\n\n<p>The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT\'s answer).</p>\n\n<p>If you\'re dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.</p>\n'}, {'answer_id': 233505, 'author': 'Marc Gravell', 'author_id': 23354, 'author_profile': 'https://Stackoverflow.com/users/23354', 'pm_score': 11, 'selected': True, 'text': '<p>Just stumbled into this oldie...</p>\n\n<p>To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties.</p>\n\n<p>To get it working with <code>IEnumerable&lt;T&gt;</code> you could add some wrapper methods that go via <code>AsQueryable</code> - but the code below is the core <code>Expression</code> logic needed.</p>\n\n<pre><code>public static IOrderedQueryable&lt;T&gt; OrderBy&lt;T&gt;(\n    this IQueryable&lt;T&gt; source, \n    string property)\n{\n    return ApplyOrder&lt;T&gt;(source, property, "OrderBy");\n}\n\npublic static IOrderedQueryable&lt;T&gt; OrderByDescending&lt;T&gt;(\n    this IQueryable&lt;T&gt; source, \n    string property)\n{\n    return ApplyOrder&lt;T&gt;(source, property, "OrderByDescending");\n}\n\npublic static IOrderedQueryable&lt;T&gt; ThenBy&lt;T&gt;(\n    this IOrderedQueryable&lt;T&gt; source, \n    string property)\n{\n    return ApplyOrder&lt;T&gt;(source, property, "ThenBy");\n}\n\npublic static IOrderedQueryable&lt;T&gt; ThenByDescending&lt;T&gt;(\n    this IOrderedQueryable&lt;T&gt; source, \n    string property)\n{\n    return ApplyOrder&lt;T&gt;(source, property, "ThenByDescending");\n}\n\nstatic IOrderedQueryable&lt;T&gt; ApplyOrder&lt;T&gt;(\n    IQueryable&lt;T&gt; source, \n    string property, \n    string methodName) \n{\n    string[] props = property.Split(\'.\');\n    Type type = typeof(T);\n    ParameterExpression arg = Expression.Parameter(type, "x");\n    Expression expr = arg;\n    foreach(string prop in props) {\n        // use reflection (not ComponentModel) to mirror LINQ\n        PropertyInfo pi = type.GetProperty(prop);\n        expr = Expression.Property(expr, pi);\n        type = pi.PropertyType;\n    }\n    Type delegateType = typeof(Func&lt;,&gt;).MakeGenericType(typeof(T), type);\n    LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);\n\n    object result = typeof(Queryable).GetMethods().Single(\n            method =&gt; method.Name == methodName\n                    &amp;&amp; method.IsGenericMethodDefinition\n                    &amp;&amp; method.GetGenericArguments().Length == 2\n                    &amp;&amp; method.GetParameters().Length == 2)\n            .MakeGenericMethod(typeof(T), type)\n            .Invoke(null, new object[] {source, lambda});\n    return (IOrderedQueryable&lt;T&gt;)result;\n}\n</code></pre>\n\n<hr>\n\n<p>Edit: it gets more fun if you want to mix that with <code>dynamic</code> - although note that <code>dynamic</code> only applies to LINQ-to-Objects (expression-trees for ORMs etc can\'t really represent <code>dynamic</code> queries - <code>MemberExpression</code> doesn\'t support it). But here\'s a way to do it with LINQ-to-Objects. Note that the choice of <code>Hashtable</code> is due to favorable locking semantics:</p>\n\n<pre><code>using Microsoft.CSharp.RuntimeBinder;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nstatic class Program\n{\n    private static class AccessorCache\n    {\n        private static readonly Hashtable accessors = new Hashtable();\n\n        private static readonly Hashtable callSites = new Hashtable();\n\n        private static CallSite&lt;Func&lt;CallSite, object, object&gt;&gt; GetCallSiteLocked(\n            string name) \n        {\n            var callSite = (CallSite&lt;Func&lt;CallSite, object, object&gt;&gt;)callSites[name];\n            if(callSite == null)\n            {\n                callSites[name] = callSite = CallSite&lt;Func&lt;CallSite, object, object&gt;&gt;\n                    .Create(Binder.GetMember(\n                                CSharpBinderFlags.None, \n                                name, \n                                typeof(AccessorCache),\n                                new CSharpArgumentInfo[] { \n                                    CSharpArgumentInfo.Create(\n                                        CSharpArgumentInfoFlags.None, \n                                        null) \n                                }));\n            }\n            return callSite;\n        }\n\n        internal static Func&lt;dynamic,object&gt; GetAccessor(string name)\n        {\n            Func&lt;dynamic, object&gt; accessor = (Func&lt;dynamic, object&gt;)accessors[name];\n            if (accessor == null)\n            {\n                lock (accessors )\n                {\n                    accessor = (Func&lt;dynamic, object&gt;)accessors[name];\n                    if (accessor == null)\n                    {\n                        if(name.IndexOf(\'.\') &gt;= 0) {\n                            string[] props = name.Split(\'.\');\n                            CallSite&lt;Func&lt;CallSite, object, object&gt;&gt;[] arr \n                                = Array.ConvertAll(props, GetCallSiteLocked);\n                            accessor = target =&gt;\n                            {\n                                object val = (object)target;\n                                for (int i = 0; i &lt; arr.Length; i++)\n                                {\n                                    var cs = arr[i];\n                                    val = cs.Target(cs, val);\n                                }\n                                return val;\n                            };\n                        } else {\n                            var callSite = GetCallSiteLocked(name);\n                            accessor = target =&gt;\n                            {\n                                return callSite.Target(callSite, (object)target);\n                            };\n                        }\n                        accessors[name] = accessor;\n                    }\n                }\n            }\n            return accessor;\n        }\n    }\n\n    public static IOrderedEnumerable&lt;dynamic&gt; OrderBy(\n        this IEnumerable&lt;dynamic&gt; source, \n        string property)\n    {\n        return Enumerable.OrderBy&lt;dynamic, object&gt;(\n            source, \n            AccessorCache.GetAccessor(property), \n            Comparer&lt;object&gt;.Default);\n    }\n\n    public static IOrderedEnumerable&lt;dynamic&gt; OrderByDescending(\n        this IEnumerable&lt;dynamic&gt; source, \n        string property)\n    {\n        return Enumerable.OrderByDescending&lt;dynamic, object&gt;(\n            source, \n            AccessorCache.GetAccessor(property), \n            Comparer&lt;object&gt;.Default);\n    }\n\n    public static IOrderedEnumerable&lt;dynamic&gt; ThenBy(\n        this IOrderedEnumerable&lt;dynamic&gt; source, \n        string property)\n    {\n        return Enumerable.ThenBy&lt;dynamic, object&gt;(\n            source, \n            AccessorCache.GetAccessor(property), \n            Comparer&lt;object&gt;.Default);\n    }\n\n    public static IOrderedEnumerable&lt;dynamic&gt; ThenByDescending(\n        this IOrderedEnumerable&lt;dynamic&gt; source, \n        string property)\n    {\n        return Enumerable.ThenByDescending&lt;dynamic, object&gt;(\n            source, \n            AccessorCache.GetAccessor(property), \n            Comparer&lt;object&gt;.Default);\n    }\n\n    static void Main()\n    {\n        dynamic a = new ExpandoObject(), \n                b = new ExpandoObject(), \n                c = new ExpandoObject();\n        a.X = "abc";\n        b.X = "ghi";\n        c.X = "def";\n        dynamic[] data = new[] { \n            new { Y = a },\n            new { Y = b }, \n            new { Y = c } \n        };\n\n        var ordered = data.OrderByDescending("Y.X").ToArray();\n        foreach (var obj in ordered)\n        {\n            Console.WriteLine(obj.Y.X);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 370126, 'author': 'InfoStatus', 'author_id': 41385, 'author_profile': 'https://Stackoverflow.com/users/41385', 'pm_score': 3, 'selected': False, 'text': "<p>I've stumble this question looking for Linq multiple orderby clauses\nand maybe this was what the author was looking for</p>\n\n<p>Here's how to do that:</p>\n\n<pre><code>var query = pets.OrderBy(pet =&gt; pet.Name).ThenByDescending(pet =&gt; pet.Age);    \n</code></pre>\n"}, {'answer_id': 649026, 'author': 'Mike Christiansen', 'author_id': 29249, 'author_profile': 'https://Stackoverflow.com/users/29249', 'pm_score': 2, 'selected': False, 'text': "<p>An alternate solution uses the following class/interface.  It's not truly dynamic, but it works.</p>\n\n<pre><code>public interface IID\n{\n    int ID\n    {\n        get; set;\n    }\n}\n\npublic static class Utils\n{\n    public static int GetID&lt;T&gt;(ObjectQuery&lt;T&gt; items) where T:EntityObject, IID\n    {\n        if (items.Count() == 0) return 1;\n        return items.OrderByDescending(u =&gt; u.ID).FirstOrDefault().ID + 1;\n    }\n}\n</code></pre>\n"}, {'answer_id': 704341, 'author': 'vdhant', 'author_id': 30572, 'author_profile': 'https://Stackoverflow.com/users/30572', 'pm_score': 5, 'selected': False, 'text': "<p>Just building on what others have said. I found that the following works quite well.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; OrderBy&lt;T&gt;(this IEnumerable&lt;T&gt; input, string queryString)\n{\n    if (string.IsNullOrEmpty(queryString))\n        return input;\n\n    int i = 0;\n    foreach (string propname in queryString.Split(','))\n    {\n        var subContent = propname.Split('|');\n        if (Convert.ToInt32(subContent[1].Trim()) == 0)\n        {\n            if (i == 0)\n                input = input.OrderBy(x =&gt; GetPropertyValue(x, subContent[0].Trim()));\n            else\n                input = ((IOrderedEnumerable&lt;T&gt;)input).ThenBy(x =&gt; GetPropertyValue(x, subContent[0].Trim()));\n        }\n        else\n        {\n            if (i == 0)\n                input = input.OrderByDescending(x =&gt; GetPropertyValue(x, subContent[0].Trim()));\n            else\n                input = ((IOrderedEnumerable&lt;T&gt;)input).ThenByDescending(x =&gt; GetPropertyValue(x, subContent[0].Trim()));\n        }\n        i++;\n    }\n\n    return input;\n}\n</code></pre>\n"}, {'answer_id': 1642942, 'author': 'James McCormack', 'author_id': 71906, 'author_profile': 'https://Stackoverflow.com/users/71906', 'pm_score': 4, 'selected': False, 'text': '<p>I was trying to do this but having problems with <a href="https://stackoverflow.com/questions/41244/dynamic-linq-orderby#41262">Kjetil Watnedal\'s solution</a> because I don\'t use the inline linq syntax - I prefer method-style syntax. My specific problem was in trying to do dynamic sorting using a custom <code>IComparer</code>.</p>\n\n<p>My solution ended up like this:</p>\n\n<p>Given an IQueryable query like so:</p>\n\n<pre><code>List&lt;DATA__Security__Team&gt; teams = TeamManager.GetTeams();\nvar query = teams.Where(team =&gt; team.ID &lt; 10).AsQueryable();\n</code></pre>\n\n<p>And given a run-time sort field argument:</p>\n\n<pre><code>string SortField; // Set at run-time to "Name"\n</code></pre>\n\n<p>The dynamic OrderBy looks like so:</p>\n\n<pre><code>query = query.OrderBy(item =&gt; item.GetReflectedPropertyValue(SortField));\n</code></pre>\n\n<p>And that\'s using a little helper method called GetReflectedPropertyValue():</p>\n\n<pre><code>public static string GetReflectedPropertyValue(this object subject, string field)\n{\n    object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);\n    return reflectedValue != null ? reflectedValue.ToString() : "";\n}\n</code></pre>\n\n<hr>\n\n<p>One last thing - I mentioned that I wanted the <code>OrderBy</code> to use custom <code>IComparer</code> - because I wanted to do <a href="https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="noreferrer">Natural sorting</a>.</p>\n\n<p>To do that, I just alter the <code>OrderBy</code> to:</p>\n\n<pre><code>query = query.OrderBy(item =&gt; item.GetReflectedPropertyValue(SortField), new NaturalSortComparer&lt;string&gt;());\n</code></pre>\n\n<p>See <a href="http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html" rel="noreferrer">this post</a> for the code for <code>NaturalSortComparer()</code>.</p>\n'}, {'answer_id': 2058305, 'author': 'Sameer Alibhai', 'author_id': 2343, 'author_profile': 'https://Stackoverflow.com/users/2343', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s something else I found interesting.\nIf your source is a DataTable, you can use dynamic sorting without using Dynamic Linq</p>\n\n<pre><code>DataTable orders = dataSet.Tables["SalesOrderHeader"];\nEnumerableRowCollection&lt;DataRow&gt; query = from order in orders.AsEnumerable()\n                                         orderby order.Field&lt;DateTime&gt;("OrderDate")\n                                         select order;\nDataView view = query.AsDataView();\nbindingSource1.DataSource = view;\n</code></pre>\n\n<p>reference: <a href="http://msdn.microsoft.com/en-us/library/bb669083.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb669083.aspx</a> (Using DataSetExtensions)</p>\n\n<p>Here is one more way to do it by converting it to a DataView:</p>\n\n<pre><code>DataTable contacts = dataSet.Tables["Contact"];    \nDataView view = contacts.AsDataView();    \nview.Sort = "LastName desc, FirstName asc";    \nbindingSource1.DataSource = view;\ndataGridView1.AutoResizeColumns();\n</code></pre>\n'}, {'answer_id': 3508411, 'author': 'Adam Anderson', 'author_id': 302998, 'author_profile': 'https://Stackoverflow.com/users/302998', 'pm_score': 6, 'selected': False, 'text': '<p>Just stumbled across this question.</p>\n\n<p>Using Marc\'s ApplyOrder implementation from above, I slapped together an Extension method that handles SQL-like strings like:</p>\n\n<pre><code>list.OrderBy("MyProperty DESC, MyOtherProperty ASC");\n</code></pre>\n\n<p>Details can be found here: <a href="http://aonnull.blogspot.com/2010/08/dynamic-sql-like-linq-orderby-extension.html" rel="noreferrer">http://aonnull.blogspot.com/2010/08/dynamic-sql-like-linq-orderby-extension.html</a></p>\n'}, {'answer_id': 8660293, 'author': 'Alaa Osta', 'author_id': 456156, 'author_profile': 'https://Stackoverflow.com/users/456156', 'pm_score': 8, 'selected': False, 'text': '<p>Too easy without any complication:</p>\n<ol>\n<li>Add <code>using System.Linq.Dynamic;</code> at the top.</li>\n<li>Use <code>vehicles = vehicles.AsQueryable().OrderBy(&quot;Make ASC, Year DESC&quot;).ToList();</code></li>\n</ol>\n<p><strong>Edit</strong>: to save some time, the <strong>System.Linq.Dynamic.Core</strong> (System.Linq.Dynamic is deprecated) assembly is not part of the framework, but can be installed from nuget: <a href="https://www.nuget.org/packages/System.Linq.Dynamic.Core/" rel="noreferrer">System.Linq.Dynamic.Core</a></p>\n'}, {'answer_id': 12920204, 'author': 'joaopintocruz', 'author_id': 1139347, 'author_profile': 'https://Stackoverflow.com/users/1139347', 'pm_score': 2, 'selected': False, 'text': '<p>Thanks to Maarten (<a href="https://stackoverflow.com/questions/11431546/query-a-collection-using-propertyinfo-object-in-linq">Query a collection using PropertyInfo object in LINQ</a>) I got this solution:</p>\n\n<pre><code>myList.OrderByDescending(x =&gt; myPropertyInfo.GetValue(x, null)).ToList();\n</code></pre>\n\n<p>In my case I was working on a "ColumnHeaderMouseClick" (WindowsForm) so just found the specific Column pressed and its correspondent PropertyInfo:</p>\n\n<pre><code>foreach (PropertyInfo column in (new Process()).GetType().GetProperties())\n{\n    if (column.Name == dgvProcessList.Columns[e.ColumnIndex].Name)\n    {}\n}\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>PropertyInfo column = (new Process()).GetType().GetProperties().Where(x =&gt; x.Name == dgvProcessList.Columns[e.ColumnIndex].Name).First();\n</code></pre>\n\n<p>(be sure to have your column Names matching the object Properties)</p>\n\n<p>Cheers</p>\n'}, {'answer_id': 16046948, 'author': 'Sanchitos', 'author_id': 317832, 'author_profile': 'https://Stackoverflow.com/users/317832', 'pm_score': 3, 'selected': False, 'text': '<p>After a lot of searching this worked for me:</p>\n\n<pre><code>public static IEnumerable&lt;TEntity&gt; OrderBy&lt;TEntity&gt;(this IEnumerable&lt;TEntity&gt; source, \n                                                    string orderByProperty, bool desc)\n{\n    string command = desc ? "OrderByDescending" : "OrderBy";\n    var type = typeof(TEntity);\n    var property = type.GetProperty(orderByProperty);\n    var parameter = Expression.Parameter(type, "p");\n    var propertyAccess = Expression.MakeMemberAccess(parameter, property);\n    var orderByExpression = Expression.Lambda(propertyAccess, parameter);\n    var resultExpression = Expression.Call(typeof(Queryable), command, \n                                           new[] { type, property.PropertyType },\n                                           source.AsQueryable().Expression, \n                                           Expression.Quote(orderByExpression));\n    return source.AsQueryable().Provider.CreateQuery&lt;TEntity&gt;(resultExpression);\n}\n</code></pre>\n'}, {'answer_id': 18062130, 'author': 'user145610', 'author_id': 145610, 'author_profile': 'https://Stackoverflow.com/users/145610', 'pm_score': 0, 'selected': False, 'text': '<p>Convert List to IEnumerable or Iquerable, add using System.LINQ.Dynamic namespace, then u can mention the property names in comma seperated string to OrderBy Method which comes by default from System.LINQ.Dynamic.</p>\n'}, {'answer_id': 25034533, 'author': 'Richard YS', 'author_id': 1659637, 'author_profile': 'https://Stackoverflow.com/users/1659637', 'pm_score': 2, 'selected': False, 'text': '<p>You can convert the IEnumerable to IQueryable.</p>\n\n<pre><code>items = items.AsQueryable().OrderBy("Name ASC");\n</code></pre>\n'}, {'answer_id': 37251268, 'author': 'Arindam', 'author_id': 6198269, 'author_profile': 'https://Stackoverflow.com/users/6198269', 'pm_score': -1, 'selected': False, 'text': '<pre><code>var result1 = lst.OrderBy(a=&gt;a.Name);// for ascending order. \n var result1 = lst.OrderByDescending(a=&gt;a.Name);// for desc order. \n</code></pre>\n'}, {'answer_id': 47462935, 'author': 'M.Hassan', 'author_id': 3142139, 'author_profile': 'https://Stackoverflow.com/users/3142139', 'pm_score': 2, 'selected': False, 'text': '<p>This answer is a response to the comments that need an example for the solution provided by  <a href="https://stackoverflow.com/a/74735/3142139">@John Sheehan - Runscope</a></p>\n<blockquote>\n<p>Please provide an example for the rest of us.</p>\n</blockquote>\n<p>in DAL (Data Access Layer),</p>\n<p><strong>The IEnumerable version:</strong></p>\n<pre><code>public  IEnumerable&lt;Order&gt; GetOrders()\n{\n    // i use Dapper to return IEnumerable&lt;T&gt; using Query&lt;T&gt;\n    //.. do stuff\n\n    return orders  // IEnumerable&lt;Order&gt;\n}\n</code></pre>\n<p><strong>The IQueryable version</strong></p>\n<pre><code>public IQueryable&lt;Order&gt; GetOrdersAsQuerable()\n{\n    IEnumerable&lt;Order&gt; qry= GetOrders();\n\n    // use the built-in extension method  AsQueryable in  System.Linq namespace\n    return qry.AsQueryable();            \n}\n</code></pre>\n<p>Now you can use the IQueryable  version to bind, for example GridView in Asp.net and benefit for sorting (you can\'t sort using IEnumerable version)</p>\n<p>I used Dapper as ORM and build IQueryable version and utilized sorting in GridView in asp.net  so easy.</p>\n'}, {'answer_id': 49212617, 'author': 'Aminur Rahman', 'author_id': 5644299, 'author_profile': 'https://Stackoverflow.com/users/5644299', 'pm_score': 3, 'selected': False, 'text': '<p>First Install Dynamic \n<strong>Tools --> NuGet Package Manager --> Package Manager Console</strong></p>\n\n<pre><code>install-package System.Linq.Dynamic\n</code></pre>\n\n<p>Add <strong>Namespace</strong> <code>using System.Linq.Dynamic;</code></p>\n\n<p>Now you can use <code>OrderBy("Name, Age DESC")</code></p>\n'}, {'answer_id': 53921180, 'author': 'Masoud Darvishian', 'author_id': 1402749, 'author_profile': 'https://Stackoverflow.com/users/1402749', 'pm_score': 3, 'selected': False, 'text': '<p>Use dynamic <code>linq</code></p>\n\n<p>just add <code>using System.Linq.Dynamic;</code></p>\n\n<p>And use it like this to order all your columns:</p>\n\n<pre><code>string sortTypeStr = "ASC"; // or DESC\nstring SortColumnName = "Age"; // Your column name\nquery = query.OrderBy($"{SortColumnName} {sortTypeStr}");\n</code></pre>\n'}, {'answer_id': 60711480, 'author': 'k1developer', 'author_id': 3607574, 'author_profile': 'https://Stackoverflow.com/users/3607574', 'pm_score': 2, 'selected': False, 'text': '<p>You can use this:</p>\n\n<pre><code>        public List&lt;Book&gt; Books(string orderField, bool desc, int skip, int take)\n{\n    var propertyInfo = typeof(Book).GetProperty(orderField);\n\n    return _context.Books\n        .Where(...)\n        .OrderBy(p =&gt; !desc ? propertyInfo.GetValue(p, null) : 0)\n        .ThenByDescending(p =&gt; desc ? propertyInfo.GetValue(p, null) : 0)\n        .Skip(skip)\n        .Take(take)\n        .ToList();\n}\n</code></pre>\n'}, {'answer_id': 64088037, 'author': 'Francis Shaw', 'author_id': 9614021, 'author_profile': 'https://Stackoverflow.com/users/9614021', 'pm_score': 1, 'selected': False, 'text': '<p>you can do it like this for multiple order by</p>\n<pre><code>IOrderedEnumerable&lt;JToken&gt; sort;\n\nif (query.OrderBys[0].IsDESC)\n{\n    sort = jarry.OrderByDescending(r =&gt; (string)r[query.OrderBys[0].Key]);\n}\nelse\n{\n    sort = jarry.OrderBy(r =&gt;\n        (string) r[query.OrderBys[0].Key]); \n}\n\nforeach (var item in query.OrderBys.Skip(1))\n{\n    if (item.IsDESC)\n    {\n        sort = sort.ThenByDescending(r =&gt; (string)r[item.Key]);\n    }\n    else\n    {\n        sort = sort.ThenBy(r =&gt; (string)r[item.Key]);\n    }\n}\n</code></pre>\n'}, {'answer_id': 70193394, 'author': 'BenW', 'author_id': 1833408, 'author_profile': 'https://Stackoverflow.com/users/1833408', 'pm_score': -1, 'selected': False, 'text': '<p>I am able to do this with the code below. No need write long and complex code.</p>\n<pre><code> protected void sort_array(string field_name, string asc_desc)\n        {\n\n            objArrayList= Sort(objArrayList, field_name, asc_desc);\n        }\n\n        protected List&lt;ArrayType&gt; Sort(List&lt;ArrayType&gt; input, string property, string asc_desc)\n        {\n            if (asc_desc == &quot;ASC&quot;)\n            {\n\n                return input.OrderBy(p =&gt; p.GetType()\n                                           .GetProperty(property)\n                                           .GetValue(p, null)).ToList();\n            }\n            else\n            {\n                return input.OrderByDescending(p =&gt; p.GetType()\n                                               .GetProperty(property)\n                                               .GetValue(p, null)).ToList();\n            }\n        }\n</code></pre>\n'}, {'answer_id': 70411214, 'author': 'Sajed', 'author_id': 10336618, 'author_profile': 'https://Stackoverflow.com/users/10336618', 'pm_score': 2, 'selected': False, 'text': '<p>You can define a dictionary from string to Func&lt;&gt; like this :</p>\n<pre><code>Dictionary&lt;string, Func&lt;Item, object&gt;&gt; SortParameters = new Dictionary&lt;string, Func&lt;Item, object&gt;&gt;()\n{\n    {&quot;Rank&quot;, x =&gt; x.Rank}\n};\n</code></pre>\n<p>And use it like this :</p>\n<pre><code>yourList.OrderBy(SortParameters[&quot;Rank&quot;]);\n</code></pre>\n<p>In this case you can dynamically sort by string.</p>\n'}]
['https://Stackoverflow.com/questions/41244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1786/']