[英]using linq to orderBy in list of lists
我有以下模型:
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.Name
和Car.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()
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.