using linq to orderBy in list of lists

asp.net-mvc c# entity-framework-core linq

Question

I have the following model:

public class Person {
    public int Id {get; set; }
    public string Name {get; set; }
    public List <Car> Cars {get; set; }
}

public class Car {
    public int Id {get; set; }
    public string Make {get; set; }
    public string Color {get; set; }
}

var persons = new List<Person>(){.....}

I want to query the persons list and order it by Person.Name and Car.Make.

I want the person list to be sorted by Person.Name, and the individual person car list to be sorted by Car.Make

var entities = Persons
                .Include(h => h.Cars)
                .Where(h => h.Id == 1).OrderBy(h => h.Name).ToList(); 

Order by Person.Name works fine, but I need to order by Car.Make also. since I can't use orderBy within .Include(h => h.Cars), so I decided to order it using a foreach,

        entities.ForEach(h =>  {
            h.Cars.OrderBy(t => t.Make); 
        }); 

this didn't work. How do I make it work?

1
1
3/22/2017 7:59:30 PM

Accepted Answer

Regarding OrderBy()

The OrderBy() method returns a collection of items as opposed to ordering in-place, so you would need to set your Cars to that specific value:

entities.ForEach(h => {
     // This will order your cars for this person by Make
     h.Cars = h.Cars.OrderBy(t => t.Make).ToList(); 
}); 

You could potentially handle this within a single call with a Select() statement as well to avoid iterating through the list once more with a ForEach() call:

var entities = Persons.Include(h => h.Cars)
                      .Where(h => h.Id == 1)
                      .OrderBy(h => h.Name)
                      // .ToList() (Use this if calling directly from EF)
                      .Select(p => new Person(){
                          Id = p.Id,
                          Name = p.Name,
                          Cars = p.Cars.OrderBy(c => c.Name).ToList()
                      });
4
3/22/2017 7:55:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow