Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ join and group

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

select S.*
from Singles S
join (
    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();
}
like image 442
AmITheRWord Avatar asked May 10 '11 13:05

AmITheRWord


1 Answers

How about this:

var firstSingles = Singles.GroupBy(x => x.ArtistId)
                          .Select(g => g.OrderByDescending(x => x.Released).First())
                          .ToList();
like image 104
BrokenGlass Avatar answered Sep 28 '22 21:09

BrokenGlass