User1710
User1710

Reputation: 299

Get Rank from list of object depending upon some condition

I have list of object of class which contain totalScore as one property.I want to get rank of Team depending upon totalscore of team.Here is the list of object I called it as List data= new List();

so data contain object of scoreboard class with total score property. I need rank of team depending upon totalscore.Here is the code that I try but it give result like Rank=1,2,2,3 but I need Rank=1,2,2,4 like this.

data.OrderByDescending(x => x.totalScore).GroupBy(x => x.totalScore)
    .SelectMany((g, i) => g.Select(e => new { data = e.Rank = i + 1 }))
    .ToList();

The data list contain unique team but there total score may be same so same totalscore team must be in one rank. please help me!

Upvotes: 0

Views: 778

Answers (2)

Zein Makki
Zein Makki

Reputation: 30052

If you need to update the list in-place:

int i = 0;
decimal? prevValue = null;
foreach(var item in data.OrderByDescending(x => x.totalScore))
{
    item.Rank = prevValue == item.totalScore ? i : ++i;

    prevValue = item.totalScore;
}

Upvotes: 2

Marcus
Marcus

Reputation: 8669

A different notation (which I prefer for readability) but essentially the same answer as provided by user3185569.

var i = 1;
var results = (from d in data orderby d.totalScore descending select new { Obj = d, Rank = i++ } ).ToList();

Upvotes: 0

Related Questions