[英]Distinct with group by in Linq
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
I have above table and I want to get the distinct BookType count and BookID count for each user, I am able to write this in SQL Server but when I come to LINQ I am unable to write the query.我有上面的表格,我想为每个用户获取不同的 BookType 计数和 BookID 计数,我可以在 SQL Server 中编写它,但是当我来到 LINQ 时,我无法编写查询。
I need the following output我需要以下输出
ID UserName BookType BookID
1 Krish 2 2
2 Ram 1 1
3 Raj 1 2
This should give you correct result:-这应该给你正确的结果:-
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)
});
Update:更新:
Although you agreed to answer, I somehow missed your requirement and the answer which I posted above is wrong since it fetch the maximum BookType & BookId.尽管您同意回答,但我不知何故错过了您的要求,并且我上面发布的答案是错误的,因为它获取了最大的 BookType 和 BookId。 Below is the query to fetch the distinct count:-以下是获取不同计数的查询:-
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()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.