Converting SQL Rank() to LINQ, or alternative

前端 未结 4 1966
野趣味
野趣味 2020-12-06 06:00

I have the below SQL statement that works as desired/expected. However I would like to translate it into a LINQ statement(Lambda??) so that it will fit with the rest of my

相关标签:
4条回答
  • 2020-12-06 06:16

    Based on answer from @Totero but with a lamda implementation. Higher score = higher rank.

    var rankedData = data.Select(s => new{
                        Ranking = data.Count(x => x.Value > s.Value)+1,
                        Name = s.Key,
                        Score = s.Value});
    

    For this input:

    { 100, 100, 98, 97, 97, 97, 91, 50 }
    

    You will get this output:

    • Score : Rank
    • 100 : 1
    • 100 : 1
    • 98 : 3
    • 97 : 4
    • 97 : 4
    • 97 : 4
    • 91 : 6
    • 50 : 7
    0 讨论(0)
  • If you want to simulate rank then you can use following linq query.

          var q = (from s in class.student
                    select new
                    {
                        Name = s.Name,
                        Rank = (from o in class.student
                                where o.Mark > s.Mark && o.studentId == s.studentId
                                select o.Mark).Distinct().Count() + 1
                    }).ToList();
    

    you can use order by like:

          var q = (from s in class.student
                    orderby s.studentId 
                    select new
                    {
                        Name = s.Name,
                        Rank = (from o in class.student
                                where o.Mark > s.Mark && o.studentId == s.studentId
                                select o.Mark).Distinct().Count() + 1
                    }).ToList();
    

    but order by does not matter in this query.

    0 讨论(0)
  • 2020-12-06 06:30

    Here's a sample that shows how I would simulate Rank() in Linq:

       var q = from s in class.student
                     orderby s.Age descending
                     select new { 
                         Name = s.name, 
                         Rank = (from o in class.student
                                 where o.mark > s.mark
                                 select o).Count() + 1 
                     };
    
    0 讨论(0)
  • 2020-12-06 06:32

    LINQ has rank funcionality built in, but not in the query syntax. When using the method syntax most linq functions come in two versions - the normal one and one with a rank supplied.

    A simple example selecting only every other student and then adding the index in the resulting sequence to the result:

    var q = class.student.OrderBy(s => s.studentId).Where((s, i) => i % 2 == 0)
    .Select((s,i) => new
    {
      Name = s.Name,
      Rank = i
    }
    
    0 讨论(0)
提交回复
热议问题