gpt4 book ai didi

c# - Linq 按 ID 加入并按名称排序

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:00 25 4
gpt4 key购买 nike

假设我有 2 个对象集合(我对 here 中的示例做了一些修改)

Person magnus = new Person { Name = "Hedlund, Magnus", Id = 1 };
Person terry = new Person { Name = "Adams, Terry", Id =2 };
Person charlotte = new Person { Name = "Weiss, Charlotte", Id = 3 };

Pet barley = new Pet { Name = "Barley", Owner = 1};
Pet boots = new Pet { Name = "Boots", Owner = 2};
Pet whiskers = new Pet { Name = "Whiskers", Owner = 2};
Pet daisy = new Pet { Name = "Daisy", Owner = 3};

List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };

我现在如何根据它们的主人姓名对宠物进行排序并返回宠物集合,即我想要这样的结果:

boots, whiskers, barley, daisy.

有什么想法吗?提前致谢!

最佳答案

var query = from pet in  pets
join person in people
on pet.Owner equals person.Id
orderby person.Name
select pet;

编辑因为你想要一个“宠物集合”:

List<Pet> result = query.ToList();

关于c# - Linq 按 ID 加入并按名称排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596639/

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