假设我有2个对象集合(我从这里修改了一点例子)
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();
pets.OrderBy(x => people.First(p => p.Id == x.Owner).Name);
可以不使用Join
(如Selman22所说),但也可以使用Join
:
var result = from pet in pets
join person in people on pet.Owner equals person.Id
orderby person.Name
select pet.Name;
Join
版本应该更快,特别是对于具有许多元素的集合