2017-02-17 52 views
-3

enter image description here 如何通过LINQ获取表中用户的排名?我用VB.NET代码查找LINQ的用户排名

,如果我们有我们的表这些领域

[ID,姓名,成绩]

为了用户,我们怎么能拿到名次(行号)的分数后一个他们在我们的查询?

+3

凌?听起来太酷了。我想得到一盒 – Plutonix

+0

你不会为此使用LINQ。 – jmcilhinney

+0

当你有两个记录相同的分数,你如何确定分数是什么?在你的例子中,你有''A1''''A7“'具有相同得分'7',但''A1''具有等级'3'和''A7”'具有等级4。系统他们都分享'3',并且排名会直接跳到下一个'5'。你想怎么做? – Enigmativity

回答

0

谢谢你的男人。我用波纹管的代码,它的工作对我罚款:

 Dim query = (From P In DB.tblUserScores Order By P.Score 
              Descending Select P).AsEnumerable() 

     Dim Rank As Integer = 1 
     For Each userObj As tblUserScore In query 
      If userObj.DeviceId = DeviceID Then Exit For 
      Rank += 1 
     Next 
+0

是的,这是更好的方法,但我认为它应该返回Rank = 5(因为A1和A7都有7分数)我们该如何解决这个问题?谢谢 – Ali

0

方法如下:

Dim records = _ 
{ _ 
    New With { Key .ID = 1, Key .Name = "A1", Key .Score = 7 }, _ 
    New With { Key .ID = 2, Key .Name = "A2", Key .Score = 9 }, _ 
    New With { Key .ID = 3, Key .Name = "A3", Key .Score = 2 }, _ 
    New With { Key .ID = 4, Key .Name = "A4", Key .Score = 1 }, _ 
    New With { Key .ID = 5, Key .Name = "A5", Key .Score = 6 }, _ 
    New With { Key .ID = 6, Key .Name = "A6", Key .Score = 4 }, _ 
    New With { Key .ID = 7, Key .Name = "A7", Key .Score = 7 }, _ 
    New With { Key .ID = 8, Key .Name = "A8", Key .Score = 3 }, _ 
    New With { Key .ID = 9, Key .Name = "A9", Key .Score = 5 }, _ 
    New With { Key .ID = 10, Key .Name = "A10", Key .Score = 8 } _ 
} 

Dim query = _ 
    From r In Records _ 
    Order By r.Name Ascending 
    Order By r.Score Descending 
    Select r 

query.Dump() 

Dim rank = _ 
    query _ 
     .Select(Function (x, n) New With { Key .Record = x, Key .Rank = n + 1 }) _ 
     .ToDictionary(Function (x) x.Record.Name, Function (x) x.Rank) 

Dim name = "A9" 
Console.WriteLine("User " & name & "'s Rank is " & rank(name)) 

这给了我:

 
User A9's Rank is 6