2010-06-10 64 views
6

如何在LINQ中實現外部應用?我遇到了一些問題。C#在LINQ中應用外部應用

這是我正在使用的SQL查詢。

SELECT u.masterID 
     ,u.user 
     ,h.created 
FROM dbo.Users u 
OUTER APPLY (SELECT TOP 1 * FROM UserHistory h where h.masterID = u.masterID ORDER BY created DESC) h 

回答

3
from u in Users 
join UserHistory on u.masterID equals h.masterID into h 
select new {u.masterID, u.user, h.created.OrderByDescending().First()} 
12
from u in Users 
join UserHistory on u.masterID equals h.masterID into h 
select new { 
    u.masterID, 
    u.user, 
    Created = h.Select(x => x.created).OrderByDescending(c => c).FirstOrDefault() 
} 

或者有關聯關係:

from u in Users 
let created = u.UserHistories.Select(x => x.created).OrderByDescending(c => c).FirstOrDefault() 
select new 
{ 
    u.masterID, 
    u.user, 
    Created = created 
}