Sort a list and all its nested objects using LINQ

前端 未结 5 2095
情书的邮戳
情书的邮戳 2021-01-04 23:49

There is an organisation with several departments and each department has a few employees.

I have created the following object model:

public class O         


        
5条回答
  •  被撕碎了的回忆
    2021-01-05 00:03

    You need to do all three levels of sorting inside the objects that you return, like this (I'll show only the "Retail", the "Institutional" needs to be sorted in the same way):

    {
    "Retail", organisations
        .Where(x => x.Type == "Retail")
        .OrderBy(x => x.Code).ThenBy(x => x.Name)
        .Select(x => new Organisation {
            x.Code
        ,   x.Type
        ,   x.Name
        ,   Departments = x.Departmentsd.OrderBy(d => d.Code).ThenBy(d => d.Name)
            .Select(d => new Department {
                d.Code
            ,   d.Name
            ,   Employees = d.Employees.OrderBy(e => e.Code).ThenBy(e => e.Name).ToList()
            })
        }).ToList()
    }
    

    Since you need to select this multiple times, you may want to wrap this code in a method, and use it from several spots, like this:

    private Organisation SortedOrganisation(Organisation x) {
        return new Organisation {
            x.Code
        ,   x.Type
        ,   x.Name
        ,   Departments = x.Departmentsd.OrderBy(d => d.Code).ThenBy(d => d.Name)
            .Select(d => new Department {
                d.Code
            ,   d.Name
            ,   Employees = d.Employees.OrderBy(e => e.Code).ThenBy(e => e.Name).ToList()
            })
        };
    }
    
    ...
    
    var legalEntitiesCollectionByType = new Dictionary>
            {
                {
                    "Institutional", organisations
                        .Where(x => x.Type == "Institutional")
                        .OrderBy(x => x.Code).ThenBy(x => x.Name)
                        .Select(SortedOrganisation)
                        .ToList()
                },
                {
                    "Retail", organisations
                        .Where(x => x.Type == "Retail")
                        .OrderBy(x => x.Code).ThenBy(x => x.Name)
                        .Select(SortedOrganisation)
                        .ToList()
                }
            };
    

提交回复
热议问题