Developer
Developer

Reputation: 26173

LINQ Query multiple orderby of joined tables

I have following LinQ query

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

which runs fine, but it is not doing second orderby using ThenBy ThenBy(g => g.C.OrderBy(c => c.CCode) What am I missing?

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

Upvotes: 0

Views: 453

Answers (1)

Muhammad Vakili
Muhammad Vakili

Reputation: 708

You didn't want to order the main list, you are looking for a way to order inner list inside of outer one, I think. So below code will do it for you:

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

Upvotes: 1

Related Questions