Sort a list and all its nested objects using LINQ

前端 未结 5 2078
情书的邮戳
情书的邮戳 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条回答
  •  旧时难觅i
    2021-01-05 00:21

    You can sort before :

        organisations.ToList().ForEach(o => o.Departments = o.Departments.OrderBy(d => d.Code).ToList());
        organisations.SelectMany(o => o.Departments).ToList().ForEach(d => d.Employees = d.Employees.OrderBy(e => e.Name).ToList());
    

    And then use the list already sorted

            var legalEntitiesCollectionByType = new Dictionary>
            {
                {
                    "Institutional", organisations
                        .Where(x => x.Type == "Institutional")
                        .ToList()
                },
                {
                    "Retail", organisations
                        .Where(x => x.Type == "Retail")
                        .ToList()
                }
            };
    

    NB : the sort is not in place, you can achieve this using a comparer

            organisations.ToList().ForEach(o => o.Departments.Sort(CreateCustomComparison));
            organisations.SelectMany(o => o.Departments).ToList().ForEach(d => d.Employees.Sort(CreateCustomComparison));
    

提交回复
热议问题