Implement Sql Server Rank and Denserank Functions in 'Lambda Expressions'

kgovindarao523-21772
Posted by kgovindarao523-21772 under C# category on | Points: 40 | Views : 3318
Hi,

The Objective of code is:

In a class there are 100 students, and in talent test they got some marks. I want to rank those students. To implement this,
In Sql Server there are two functions called Rank and Denserank .
Here i implemented those functions in C# using Lambda expressions .

In data base, My table contains Three columns
id,Name,Marks
and i used entity data model.

Here is the code:

#region Rank 

List<tableToRankStudents> data = dbContext.tableToRankStudentses.ToList();
int intRank = 0;
int intNext = 1;
Func<IGrouping<int?, tableToRankStudents>, int> getRank = (grouping) =>
{
int answer = intRank += intNext;
intNext = grouping.Count();
return answer;
};
var ranked = data
.GroupBy(v => v.Marks)
.OrderByDescending(v => v.First().Marks)
.Select(v => new
{
Items = v,
Rank = getRank(v)
})
.SelectMany(v => v.Items, (s, i) => new
{
Name = i.Names,
Marks = i.Marks,
Rank = s.Rank
});

gvRankResult.DataSource = ranked.ToList();
gvRankResult.DataBind();

#endregion Rank

#region Dense Rank

int intDenseRank = 0;
int intDenseNext = 1;
Func<IGrouping<int?, tableToRankStudents>, int> getDenseRank = (grouping) =>
{
int answer = intDenseRank = intDenseNext;
intDenseNext += 1;
return answer;
};
var DenseRanked = data
.GroupBy(v => v.Marks)
.OrderByDescending(v => v.First().Marks)
.Select(v => new
{
Items = v,
Rank = getDenseRank(v)
})
.SelectMany(v => v.Items, (s, i) => new
{
Name = i.Names,
Marks = i.Marks,
Rank = s.Rank
});

gvDenseRankResult.DataSource = DenseRanked.ToList();
gvDenseRankResult.DataBind();

#endregion Dense Rank


Thank you,
Govind

Comments or Responses

Login to post response