Use linq to find the index position, but consider value dependent relationships
What is the best way to sort by value, find the index of the item for its rank, but take into account the relationships. The index for the 5th place can have two elements, so the 6th is skipped and the next iteration starts from the 7th. Is this the best way to do this to make a group and keep track of the index?
return teamTournamentResults
.OrderByDescending(t => t.RankingPoints)
.Select((item, index) => new { Item = item, Index = index })
.Select(q => new TeamSummaryResultsModel
{
DivisionRanking = q.Index + 1,
RankingPoints= q.Item.RankingPoints,
source to share
Please read my comment on the question.
Check out an example:
List<int> mi = new List<int>(){1,2,2,5,6,7,7,7,8,9,10,10};
var qry = mi
.Select(g=>new
{
number = g,
rank = (from i in mi where i>g select i).Count()+1
});
Result:
number rank
1 12
2 10
2 10
5 9
6 8
7 5
7 5
7 5
8 4
9 3
10 1
10 1
Other helpful resources:
Converting SQL Rank () to LINQ or alternative
source to share
Do you need to know the rank for one item for all of them? If you only need it for one, then sorting is unnecessary O(n log n)
.
You can use a simple for
linear time loop to count smaller and larger items and a list of equal items. Then you just apply the same procedure to the list of equality items, but compare the command name to get a sequential order.
var equalItems = new List<Team>();
int smaller = 0, bigger = 0;
var myItem = ...;
foreach(var item in teamTournametResults)
if (item.RankingPoints > myItem.RankingPoints)
++bigger;
else
{
if (item.RankingPoints < myItem.RankingPoints)
++smaller;
else if (item != myItem)
equalItems.Add(item);
}
foreach(var item in equalItems)
if (item.Name.CompareTo(myItem.Name) > 0)
++bigger;
else
++smaller;
The resulting rank is now saved in bigger
.
source to share