title: C# Dynamic linq order by expando object
body: <p>I have a situation where I will need to sort dynamically based on a configuration from database table ascending or descending</p>
  
  <p>My Database table has column name That I will need to sort and sort order.</p>
  
  <p>I have a list of objects, in which each object has an ExpandoObject.</p>
  
  <p>My Class looks like this</p>
  
  <pre><code>  public class Customer: Base {
      public string Name { get; set;}
      public string City { get; set;}
      public string Address { get; set;}
      public string State { get; set;}
      public int Id { get; set;}
      public DateTime Dob { get; set;}
      public int Age{ get; set;}
      public dynamic custom = new ExpandoObject();
   } 
  </code></pre>
  
  <p>Customer class has an ExpandoObject in order to store additional properties also called as custom properties which are configurable per Customer.</p>
  
  <p>I have a table which has configurations for sorting, it has the Column names and sort order
  such as </p>
  
  <pre><code>ColName     SortOrder
  
  City        Asc
  Name        Desc
  custom_XYZ  Asc   //this means this is a custom column 
  </code></pre>
  
  <p>All the column names starting with custom_(Property Name) are stored in expando object which in turn is a dictionary.</p>
  
  <p>Right now I am using the below code to do dynamic linq orderBy</p>
  
  <pre><code>var sortList; // this list has the sorting list with type {string:ColName: bool:Asc}
  var customers; //holds the list of customer objects with custom fields in expando
  
  var col = sortList[0];
  var propertyInfo = typeof(Student).GetProperty(col.ColName);    
  var sortedData= customers.OrderBy(x =&gt; propertyInfo.GetValue(x, null));
  
  for(int i = 1; i&lt;sortList.Count()-1;i++){
    var col1 = sortList[i];
    var prop = typeof(Student).GetProperty(col1.ColName); 
    if(col1.asc)   
      sortedData = sortedData.ThenBy(n =&gt; param2.GetValue(n, null));
    else
      sortedData = sortedData.ThenByDescending(n =&gt; param2.GetValue(n, null));
  }
  </code></pre>
  
  <p>could someone help me on how could I sort data in custom object which is of type ExpandoObject.</p>
  
  <p>ExpandoObject actually wraps the properties as a Dictionary internally so could someone help me on how could I sort the whole object based on  the value of a Dictionary corresponding to a Key (which is columnName)</p>