代码之家  ›  专栏  ›  技术社区  ›  Illuminati

在复杂对象上使用动态LINQ排序

  •  0
  • Illuminati  · 技术社区  · 14 年前

    我有一个使用动态LINQ执行排序的对象列表。

    物体是这样的,

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

    我用动态Linq库来排序,

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

    如果传递的排序键具有列表的有效属性名(例如Vendor),则此操作很好

    问题是,如何对复杂对象执行此操作。

    假设我有另一个对象,它是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;}
            ..
    
    
    }
    

    如果我想使排序足够动态,以便能够从SampleDTO的直接属性或OtherDTO的属性进行排序(例如需要在OtherDTO.LineId上排序)

    实现这一目标的可能途径是什么?

    /BB公司

    2 回复  |  直到 14 年前
        1
  •  2
  •   Steven    14 年前

    你可以这样做:

    list.OrderBy("OtherDTO.LineId");
    
        2
  •  4
  •   Alastair Pitts    14 年前

    为什么不使用lamba语法。

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

    这样做的好处是不依赖硬编码字符串

    推荐文章