简体   繁体   English

Linq to SQL组并排名前25位

[英]Linq to SQL group and count top 25

I have two tables in my database who looks like this: 我的数据库中有两个表,它们看起来像这样:

User: 用户:

userid(int)
username(varchar)

Score: 得分:

scoreid(int)
result(bit)
attackinguserid(int) (same as User.userid)

They also contain other information but that's not important right now. 它们还包含其他信息,但这并不重要。 What i want is to get the top 25 users who has score = true and display them like this: 我想要得到的是得分= true的前25位用户,并按以下方式显示他们:

Username: Won:
Peter     28
Mike      25
Kim       20

And so on... The code I have been trying is this: 依此类推...我一直在尝试的代码是这样的:

var winners = (from s in dc.Scores
                       from u in dc.Users
                       where (s.result) && (s.attackinguserid == u.userid)
                       group u by s
                       into groups
                       select new
                                  {
                                      Username= groups.Key,
                                      Won= groups.Count()
                                  }
                      ).OrderByDescending(x => x.Seire).Distinct().Take(25);

        gvBestPlayers.DataSource = winners; //gvBestPlayers = gridview
        gvBestPlayers.DataBind();

But this gives me error on the DataBind(). 但这给我在DataBind()上的错误。 The error: NotSupportedException was unhandled by user code. 错误:用户代码未处理NotSupportedException。 The member 'System.Web.UI.Page.Title' has no supported translation to SQL. 成员'System.Web.UI.Page.Title'不支持SQL转换。

Solved it my self. 解决了我的自我。 Here is the working code: 这是工作代码:

var winners = (from s in dc.Scores 
               from u in dc.Users 
               where (s.result) && (s.attackinguserid == u.userid) 
               group s by u 
               into groups 
               select new 
               { 
                   Username= groups.Key.username, 
                   Won= groups.Count() 
               }).OrderByDescending(x => x.Seire).Distinct().Take(25).ToList(); 

gvBestPlayers.DataSource = winners; 
gvBestPlayers.DataBind();

try this.. 尝试这个..

var a = (from s in dc.Scores
                     join u in dc.Users on s.attackinguserid equals u.userid
                     let count = dc.Scores.Where(id => id.attackinguserid == u.userid ).Count()
                     where s.result == true
                     select new { Username = u.username, Won = count }).ToList().Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM