Search code examples
c#linqsql-order-bydynamic-linq

Sort using dynamic LINQ on a complex object


I have a list of Objects on which I use dynamic LINQ to perform sorting.

The object is like this,

public class SampleDTO
    {
        public string Vendor { get; set;}
        public string Invoice { get; set; }
         ..
         ..

}

And I use Dynamic Linq library to sort this,

var list= new List<SampleDTO>();
list.OrderBy("Vendor");

This works fine if I pass a sort key with a valid property name of the list ( e.g. Vendor )

The problem is, how to do this for a complex object.

Assume I have a another object which is a property of the SampleDTO

public class SampleDTO
    {
        public string Vendor { get; set;}
        public string Invoice { get; set; }
        public OtherDTO OtherDTO{get;set; }
         ..

}

public class OtherDTO 
{
        public string LineId{ get; set;}
        ..


}

And if I want to make the sorting dynamic enough so that I should be able to sort from a direct property of the SampleDTO or on a property of a OtherDTO ( e.g need to sort on OtherDTO.LineId )

What are the possible ways of achieving this?

/BB


Solution

  • You can do this:

    list.OrderBy("OtherDTO.LineId");