开发者

LINQ join and group

开发者 https://www.devze.com 2023-03-05 01:29 出处:网络
I\'m new to LINQ, and I\'m trying to convert this SQL query into its LINQ equivalent: select S.* from Singles S

I'm new to LINQ, and I'm trying to convert this SQL query into its LINQ equivalent:

select S.*
from Singles S
jo开发者_如何学Goin (
    select max(SingleId) as SingleId
    from Single 
    group by ArtistId) S2 on S2.SingleId = S.SingleId
order by Released desc

The table looks like this:

 -----------
| Singles   |
|-----------|
| SingleID  |
| ArtistId  |
| Released  |
| Title     |
| .....     |
 -----------

and so on... And contains for example these items:

SingleID   ArtistID    Released    Title
1          1           2011-05-10  Title1
2          1           2011-05-10  Title2
3          2           2011-05-10  Title3
4          3           2011-05-10  Title4
5          4           2011-05-10  Title5
6          2           2011-05-10  Title6
7          3           2011-05-10  Title7
8          5           2011-05-10  Title8
9          6           2011-05-10  Title9

So I'm trying to get the latest singles, but only one per artist. Could anyone help me? :) Maybe there's even a better way to write the query?

Update:

To answer the questions posted in the comments: We're using Microsoft SQL Server, and LINQ to NHibernate.

Here's a sample that we're using right now, that returns the latest singles, without grouping by artistid:

public Single[] GetLatest()
{
    IQueryable<Single> q;
    q = from s in _sess.Query<Single>()
        where s.State == State.Released
        orderby s.Released descending
        select s;

    return q.Take(20).ToArray();
}


How about this:

var firstSingles = Singles.GroupBy(x => x.ArtistId)
                          .Select(g => g.OrderByDescending(x => x.Released).First())
                          .ToList();


Something like this should work.

var query = from s in db.Singles
            group s by s.ArtistID into sg
            let firstSingle = sg.OrderByDescending(r => r.SingleID).FirstOrDefault()
            select new
            {
              ArtistID = sg.Key,
              SingleID = firstSingle.SingleID,
              Released = firstSingle.Released,
              Title = firstSingle.Title,
            }


singles
    .OrderByDescending(s => s.SingleID)
    .GroupBy(s => s.SingerID, (id, s) => new
    {
         SingleID = id,
         Title = s.First().Title
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消