c# - 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 , want distinct booktype count , bokkid count each user, able write in sqlserver when come linq unable write query.
i need following output,
id username booktype bookid 1 krish 2 2 2 ram 1 1 3 raj 1 2
this should give 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 agreed answer, somehow missed requirement , answer posted above wrong since fetch maximum booktype & bookid. below query fetch 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() });
Comments
Post a Comment