15

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 DAL. However I cannot see to figure out how to simulate Rank() in LINQ.

The reason I posted it here, which is maybe in error, is to see if anyone has an alternative to the Rank() statement so that I can get this switched over. Alternatively, if there is a way to represent Rank() in LINQ that would be appreciated also.

USE CMO

SELECT      vp.[PersonID] AS [PersonId]
            ,ce.[EnrollmentID]
            ,vp.[FirstName]
            ,vp.[LastName]
            ,ce.[EnrollmentDate]
            ,ce.[DisenrollmentDate]
            ,wh.WorkerCategory

FROM  [dbo].[vwPersonInfo] AS vp
            INNER JOIN 
            (
                  [dbo].[tblCMOEnrollment] AS ce
                  LEFT OUTER JOIN
                        (
                              SELECT   *
                                          ,RANK()OVER(PARTITION BY EnrollmentID ORDER BY CASE WHEN EndDate IS NULL THEN 1 ELSE 2 END, EndDate DESC, StartDate DESC) AS whrank 
                              FROM  [dbo].[tblWorkerHistory]
                              WHERE WorkerCategory = 2
                        ) AS wh 
                              ON ce.[EnrollmentID] = wh.[EnrollmentID] AND wh.whrank = 1
            ) 
                  ON vp.[PersonID] = ce.[ClientID]

WHERE (vp.LastName NOT IN ('Client','Orientation','Real','Training','Matrix','Second','Not'))
AND (
            (wh.[EndDate] <= GETDATE())
            OR wh.WorkerCategory IS NULL
      ) 
AND (
            (ce.[DisenrollmentDate] IS NULL) 
            OR (ce.[DisenrollmentDate] >= GetDate())
      )
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
Refracted Paladin
  • 12,096
  • 33
  • 123
  • 233

4 Answers4

18

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

var items = new[]
{
    new { Name = "1", Value = 2 },
    new { Name = "2", Value = 2 },
    new { Name = "3", Value = 1 },
    new { Name = "4", Value = 1 },
    new { Name = "5", Value = 3 },
    new { Name = "6", Value = 3 },
    new { Name = "7", Value = 4 },
};
  
var q = from s in items
    orderby s.Value descending
    select new 
    { 
        Name = s.Name, 
        Value = s.Value,
        Rank = (from o in items
                where o.Value > s.Value
                select o).Count() + 1 
    };

foreach(var item in q)
{
    Console.WriteLine($"Name: {item.Name} Value: {item.Value} Rank: {item.Rank}");
}

OUTPUT

Name: 7 Value: 4 Rank: 1
Name: 5 Value: 3 Rank: 2
Name: 6 Value: 3 Rank: 2
Name: 1 Value: 2 Rank: 4
Name: 2 Value: 2 Rank: 4
Name: 3 Value: 1 Rank: 6
Name: 4 Value: 1 Rank: 6
Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233
Totero
  • 2,524
  • 20
  • 34
  • 2
    To me, this feels like E=mc^2 .. an incredibly simple solution to a relatively complex problem – Ody Aug 14 '15 at 13:57
  • 6
    As far as my tests go, it seems that I am creating one separate query per result in the outer query. This becomes problematic for even a few thousand results and so this method seems bounded. – sshine Oct 19 '15 at 10:08
  • 2
    I like your thinking for this solution! I never thought to look at it that way. Well done! I ended up using lamda implementation but based on the same concept: var rankedData = data.Select(s => new{ Ranking = data.Count(x => x.Value > s.Value)+1, Name = s.Key, Score = s.Value}); – Daniel Kereama Oct 27 '16 at 04:26
  • 1
    As of using this with Ef Core 2.1 it generates single SQL query – Ramūnas Dec 28 '18 at 12:26
8

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
}
Anders Abel
  • 67,989
  • 17
  • 150
  • 217
  • 3
    Is this not strictly for materialized lists, or does it actually generate SQL that corresponds to the ranking? – sshine Oct 19 '15 at 10:07
  • 2
    When I try to use this, I keep getting the message "LINQ does not recognize the method..." until I remove the where clause. It doesn't seem to like the 2 parameters in parenthesis. – Bpainter Dec 09 '15 at 20:09
  • 1
    This should be the accepted answer, the accepted one being of terrible performance! – Vincent V. Nov 12 '16 at 15:58
  • 2
    Note that this will not handle ties. If two items have the same measure, they will be given different ranks. – Paul Chernoch Jan 14 '17 at 17:05
4

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.

Manoj Pilania
  • 664
  • 1
  • 7
  • 18
1

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
Daniel Kereama
  • 911
  • 9
  • 17