与Linq中的群组不同

时间:2015-09-30 10:51:46

标签: c# sql-server linq linq-to-sql

ID  UserName    BookType    bookID

1   Krish   1   1
1   Krish   1   2
1   Krish   2   1
1   Krish   2   2
2   Ram     1   1    
3   Raj     1   1
3   Raj     1   2

我有上面的表格,我希望为每个用户获取不同的booktype计数和bokkID计数,我能够在sqlserver中写这个,但是当我来到LINQ时无法编写查询。

我需要以下输出,

ID  UserName    BookType    bookID

1   Krish   2   2
2   Ram     1   1 
3   Raj     1   2

1 个答案:

答案 0 :(得分:9)

这应该给你正确的结果: -

var result = Userlist.GroupBy(x => new { x.ID, x.UserName })
                     .Select(x => new
                                 {
                                     ID = x.Key.ID,
                                     UserName = x.Key.UserName,
                                     BookType = x.Max(z => z.BookType),
                                     BookId = x.Max(z => z.BookId)
                                 });

<强>更新

虽然您同意回答,但我错过了您的要求,上面发布的答案是错误的,因为它获取了最大的BookType&amp; BOOKID。以下是获取非重复计数的查询: -

var result = Userlist.GroupBy(x => new { x.ID, x.UserName })
                     .Select(x => new
                         {
                            ID = x.Key.ID,
                            UserName = x.Key.UserName,
                            BookType = x.Select(z => z.BookType).Distinct().Count(),
                            BookId = x.Select(z => z.BookId).Distinct().Count()
                         });