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

linq查询联接表的多个orderby

  •  0
  • Developer  · 技术社区  · 6 年前

    我有以下LINQ查询

       var CGTABLE = (from cg in DbContext.CGTABLE
                                  join tcg in DbContext.TCGTABLE on new { cg.CGroupId } equals new { tcg.CGroupId }                                                                    
                                  where tcg.TId == TId
                                  select new  {
                                      CGroupId = cg.CGroupId,
                                      CGroupCode = cg.CGroupCode,                                      
                                      Description = cg.Description,                                      
                                      C = cg.C,
                                      DisplayOrder = cg.DisplayOrder
                                  }).ToList();
    
            CGTABLE = CGTABLE.OrderBy(g => g.DisplayOrder).ThenBy(g => g.C.OrderBy(c => c.CCode)).ToList();
    

    运行良好,但使用Thenby不会执行第二个顺序 ThenBy(g => g.C.OrderBy(c => c.CCode) 我错过了什么?

    Sample data for better understanding.
    Data in Tables
    2
      1
      2
      4
      3
    1
      4
      5
      2
      1
    3
      3
      1
    
    Should output after both outer and inner list ordered by
    1
      1
      2
      3
      4
    2
      1
      2
      4
      5
    3
      1
      3
    
    But Currently it is showing
    1
      4
      5
      2
      1
    2
      1
      2
      4
      3
    3
      3
      1
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Muhammad Vakili    6 年前

    你不想订购主列表,我想你是在寻找一种方法,在外部列表里面订购内部列表。 所以下面的代码将为您提供:

    var CGTABLE = (
        from cg in DbContext.CGTABLE
        join tcg in DbContext.TCGTABLE on new { cg.CGroupId } equals new { tcg.CGroupId }                                                                    
        where tcg.TId == TId
        select new  {
            CGroupId = cg.CGroupId,
            CGroupCode = cg.CGroupCode,                                      
            Description = cg.Description,                                      
            C = cg.C.OrderBy(x => x.CCode),
            DisplayOrder = cg.DisplayOrder
       }).ToList();
    
       CGTABLE = CGTABLE.OrderBy(g => g.DisplayOrder).ToList();