在子查询问题中具有指定行数的LINQ查询

时间:2010-04-28 21:22:23

标签: linq subquery

我正在尝试在LINQ中编写以下查询,但似乎无法使其正确。

select p.*
from Person p
inner join PersoniPhones i ON p.PersonID = i.PersonID
where p.PersonID in
(
    SELECT PersonID
    FROM
        (
        SELECT Top 10 PersonID, iPhoneID
        FROM iPhone
        ORDER BY LastPlayedDate DESC
        ) as t
)

我已尝试过以下操作,但无法正确返回

        var tenIPhones = from phone in context.PersonIPhones
                         .OrderByDescending(i => i.LastPlayedDate)
                         .Take(10)
                         select new { phone.PersonID, phone.IPHoneID};
        var people = from p in context.Person
                 join t in tenIPhones on p.PersonID equals t.PersonID
                 select p;

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

怎么样?
var subsetPhone = iPhones.OrderByDescending(x => x.LastPlayedDate).Take(10).Select(x => new { PersonId = x.PersonId, iPhoneId = x.iPhoneId });
var people = persons.Where(x => subsetPhone.Where(y => y.PersonId == x.Id).Count() > 0);

答案 1 :(得分:1)

这适用于LinqPad通知IPhoneID和 IPHoneID

var tenIPhones = (from i in PersoniPhones
    .OrderByDescending(i => i.LastPlayedDate)
    .Take(10)
    select new { i.PersonID, i.IPhoneID});

tenIPhones.Dump();  

var people = from p in Persons
         join t in tenIPhones on p.PersonID equals t.PersonID
         select p;

people.Dump();