Linq按ID加入并按名称排序

时间:2014-03-23 20:27:43

标签: c# linq

假设我有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.

有什么想法吗? Thx提前!

3 个答案:

答案 0 :(得分:3)

pets.OrderBy(x => people.First(p => p.Id == x.Owner).Name);

答案 1 :(得分:3)

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

修改因为你想要一个&#34;宠物集合&#34;:

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

答案 2 :(得分:2)

可以在没有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版本应该更快,特别是对于包含许多元素的集合。