[英]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.