gpt4 book ai didi

c# - 在列表列表中使用 linq to orderBy

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:32 24 4
gpt4 key购买 nike

我有以下模型:

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,所以我决定使用 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()
});

关于c# - 在列表列表中使用 linq to orderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42960857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com