使用linq命令列表中的orderBy

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

我有以下型號:

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>(){.....}

我想查詢人員列表並按Person.NameCar.Make

我希望人員列表按Person.Name排序,個人人員列表由Car.Make排序

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

Person.Name工作正常,但我需要通過Car.Make訂購。因為我不能在.Include(h => h.Cars),使用orderBy .Include(h => h.Cars),所以我決定使用foreach來命令它,

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

這沒用。我如何使其工作?

一般承認的答案

關於OrderBy()

OrderBy()方法返回一個項集合,而不是就地排序,因此您需要將Cars設置為該特定值:

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

您可以使用Select()語句在單個調用中處理此問題,以避免使用ForEach()調用再次遍歷列表:

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow