tags:

views:

56

answers:

2

I'm trying to write the following query in LINQ, but can't seem to get it correct.

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
)

I've tried the following, but it doesn't return correctly

        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;

Any ideas?

+1  A: 

What about

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);
Tejs
That worked. Thanks. I don't understand why my code doesn't work, but this works, so I'm good.
John
+1  A: 

This works in LinqPad notice IPhoneID and not 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();
Nicholas Murray
What is .Dump() ?
John
If you use LinqPad you can output the resultset by using .Dump() - pretty handy!
Nicholas Murray
The ID wasn't the issue. That was just a mistype when I translated our actual production code into a demo example. The issue is that the code generates the wrong SQL and returns too many rows.
John
@John - Unfortunately my Telepathy powers are weak tonight and I went by the code you posted ;->
Nicholas Murray
That comment deserves a +1
BlueRaja - Danny Pflughoeft