Linq订购子表

时间:2010-04-16 09:23:32

标签: asp.net linq

我的问题是如何通过子表对Linq查询进行排序:

表应用:

- app_id
- name

表AppStatus:

 - app_status_id
 - app_id
 - severity
 - status_date

我想查询所有应用,按最后状态严重程度排序:

app_id  name
1   first
2   second
3   third

app_status_id   app_id  severity    status_date
1   1   5   12-4-2010
2   1   2   15-4-2010
3   2   7   10-4-2010
4   3   3   13-4-2010

Now i want it sorted like:
app_id  name
3   third
1   first
2   second

任何人都可以帮我处理LINQ查询。

我已尝试过以下内容,但这不起作用:

    var apps = from apps in dc.Apps
                         orderby apps.AppStatus.LastOrDefault().severity
                         select apps;

编辑:

我会优化我的问题,它应该首先获得具有最新状态的所有应用程序(因此按状态日期),然后它应该按照上一个状态的严重性来排序该列表。

3 个答案:

答案 0 :(得分:2)

试试这个:

var apps = from apps in dc.Apps
           orderby apps.AppStatus.Max(a => a.severity)
           select apps;

根据您的评论进行编辑:

var apps = from apps in dc.Apps
           where apps.AppStatus.Count() > 0 // to prevent null reference below
           orderby apps.AppStatus.Where(a1 => a1.status_date ==
               apps.AppStatus.Max(a2 => a2.status_date)
           ).Single().severity
           select apps;

答案 1 :(得分:1)

尝试加入然后排序:

var apps = from a in dc.Apps
           join s in dc.AppStatus on a.app_id == s.app_id
           orderby s.severity
           select a;

答案 2 :(得分:0)

from app in myDC.Apps
let severity =
(
  from status in app.AppStatus
  orderby status.StatusDate descending
  select status.Severity
).First()
order by severity
select app