LINQ查询连接表的多个orderby

时间:2018-06-07 22:01:53

标签: c# linq

我有以下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 个答案:

答案 0 :(得分:1)

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

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();