I probably won't be able to explain this well enough, but here it goes...
I have a table similar to this:
Id | Foreign_Key_Id | A_Number | Some_Other_Info
1 1 100 Red
2 1 200 Blue
3 1 300 Orange
4 2 100 Green
5 2 200 Yellow
6 3 100 Brown
I want to get the max "A_Number" for a particular "Foreign_Key_Id" in this table, but also return the rest of the record so I have info from the "Some_Other_Info" column.
I've found I can accomplish this via a query like this:
from x in This_Table
group x by x.Foreign_Key_Id into g
orderby g.Max(x => x.A_Number) descending
select g.Where (x => x.Foreign_Key_Id == g.Key).OrderByDescending (x => x.A_Number).First()
Edit: Or possibly this more concise query:
from x in This_Table
group x by x.Foreign_Key_Id into g
let maxANumber = g.Max(x => x.A_Number)
orderby maxANumber descending
select g.Where(x => x.A_Number == maxANumber).First()
Although I'm not quite sure which record it would take if one Foreign_Key_Id had two records with the same "A_Number" value (which is possible in the table I am referring to, I would just need to take the most recent one).
Which in my example I believe would return:
Id | Foreign_Key_Id | A_Number | Some_Other_Info
3 1 300 Orange
5 2 200 Yellow
6 3 100 Brown
It seems like there has to be a way to do this in an easier fashion (that makes for a faster query than the one I came up with), I just can't figure out how.
Thanks in advance.