LINQ加入和组

时间:2011-05-10 13:33:27

标签: c# .net sql linq nhibernate

我是LINQ的新手,我正在尝试将此SQL查询转换为其LINQ等效项:

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

表格如下:

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

依旧...... 并包含例如这些项目:

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

所以我想要获得最新的单曲,但每个艺术家只有一个。谁能帮助我? :) 也许甚至有更好的方法来编写查询?

更新

回答评论中发布的问题: 我们正在使用Microsoft SQL Server和LINQ to NHibernate。

以下是我们现在正在使用的示例,它会返回最新的单曲,而不会被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();
}

3 个答案:

答案 0 :(得分:5)

这个怎么样:

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

答案 1 :(得分:1)

这样的事情应该有效。

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,
            }

答案 2 :(得分:0)

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