On a complicated object, sort using dynamic LINQ

c# dynamic-linq linq sql-order-by

Question

I have a list of objects that I can sort using dynamic LINQ.

The item looks like this:

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

}

And to sort this, I use the Dynamic Linq library.

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

If I provide a sort key that is a legitimate property name for the list, everything goes well ( e.g. Vendor )

How to do this for a complicated entity is the issue.

Consider the case when I have another object whose property is 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;}
        ..


}

Additionally, if I want the sorting to be sufficiently dynamic, I may sort based on a direct property of the SampleDTO or a property of an OtherDTO ( e.g need to sort on OtherDTO.LineId )

What are the potential approaches to doing this?

/BB

1
0
11/25/2010 11:38:47 AM

Accepted Answer

What you can do is:

list.OrderBy("OtherDTO.LineId");
2
11/25/2010 11:41:59 AM

Popular Answer

use the lambda syntax instead.

list.OrderBy(sample => sample.OtherDto.LineId);

The benefit of this is that it is not dependent on hard-coded strings.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow