LINQ加入订单然后结果排序依据

时间:2014-10-06 21:02:08

标签: c# linq join sql-order-by

我有一个LINQ来构建一个建筑物列表,其中包含一个由用户列表组成的字段:

List<Building> buildings = (from b in db.Buildings
    join u in db.BuildingUsers on b.BuildingId equals u.BuildingId into bUsers
    orderby b.BuildDate descending
    select Building.Create(b, bUsers)).ToList();

UserName并不总是我想要的用户。我真正想要的是第一个输入的用户,我认为假设它是具有最低UserID的BuildingUser是正确的。所以我按顺序执行:

List<Building> buildings = (from b in db.Buildings
    join u in db.BuildingUsers on b.BuildingId equals u.BuildingId into bUsers
    orderby u.UserId ascending
    select Building.Create(b, bUsers)).ToList();

这很有效,除了现在我的整体建筑物清单处于尴尬的顺序。 bUsers以正确的顺序传递给Create方法,我处理FirstOrDefault()以获取第一个用户并处理其余用户。我希望构建列表的最终结果由BuildDate按顺序排列。

List<Building> buildings = (from b in db.Buildings
    join u in db.BuildingUsers on b.BuildingId equals u.BuildingId into bUsers
    orderby u.UserId ascending, b.BuildDate descending
    select Building.Create(b, bUsers)).ToList();

当然这不起作用,因为现在它首先按UserId排序,然后按BuildDate排序,但结果并不完全正确。

所以我想要一个orderby用于Join,以及一个不同的orderby用于主要结果。我宁愿不将它们分成多种方法,所以我不必改变构建对象的方式。

1 个答案:

答案 0 :(得分:1)

您使用orderby b.BuildDate descending是正确的,因为这是输出集合buildings中预期的排序。子汇集bUsers的排序应在将其传递给Building.Create()时执行:

List<Building> buildings = (from b in db.Buildings
                         join u in db.BuildingUsers on b.BuildingId equals u.BuildingId into bUsers
                         orderby b.BuildDate descending
                         select Building.Create(b, bUsers.OrderBy(bu => bu.UserId))).ToList();

根据您上面的说法,我建议您更改Building.Create以接受单个用户,在这种情况下,您可以在此查询中执行FirstOrDefault()

List<Building> buildings = (from b in db.Buildings
                         join u in db.BuildingUsers on b.BuildingId equals u.BuildingId into bUsers
                         orderby b.BuildDate descending
                         select Building.Create(b, bUsers.OrderBy(bu => bu.UserId).FirstOrDefault())).ToList();