Reputation: 2997
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?
Upvotes: 2
Views: 4293
Reputation: 76547
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()
});
Upvotes: 4