tags:

views:

65

answers:

3

Hello,

My question is how to sort a Linq query by a sub table:

Table Apps:

- app_id
- name

Table AppStatus:

 - app_status_id
 - app_id
 - severity
 - status_date

I would like to have a query with all the apps, sorted by the last status severity:

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

Can anyone help me with a LINQ query for this.

I tried the following already, but that didn't work:

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

Edit:

I'll refine my question, it should first get all the apps with the latest status (so by date of the status), then it should order that list by the severity of that last status.

+2  A: 

Try this:

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

Edited based on your comment:

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;
Adam Maras
Thanks, but it didn't fix it all yet, it needs the last AppStatus of each App, then sort it by the severity of each last status.
Michael
Try the new version on for size.
Adam Maras
I think this fixed it indeed, i removed the part of the where app.AppStatusCount() > 0, because i want to show the app even when it has had no status.Thanks!
Michael
If that's the case, I believe you're going to have to modify the `orderby` clause to do a null check on the return value of the `.Single()` call on line 5.
Adam Maras
+1  A: 

Try joining then sorting:

var apps = from a in dc.Apps
           join s in dc.AppStatus on a.app_id == s.app_id
           orderby s.severity
           select a;
Marcelo Cantos
A: 
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
David B