查找LINQ的用户排名

时间:2017-02-17 21:44:49

标签: vb.net linq ranking

enter image description here 如何通过LINQ获得用户排名?我使用VB.NET CODE

如果我们在表格中有这些字段

[id,name,score]

按用户分数排序后我们如何在查询中获得其中一个排名(行号)?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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