简体   繁体   中英

using linq to orderBy in list of lists

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM