Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto numbering in linq query

Tags:

c#

list

linq

I have list of string as this:

 var TopScores=
                list.Where(s => s.Score>2500)
                    .OrderBy(s => s.Score)
                    .Select(s => s.name)
                    .ToList();

var text=  $"{"this is name of top score students"}\n{string.Join("\n", topScores)}"

What I have is:

this is name of top score students
jim
john
mary

What I need is:

this is name of top score students
1-jim
2-john
3-mary

The problem is that the number of topScores is dynamic, how can i achive the above list?

like image 819
someone Avatar asked Dec 19 '22 23:12

someone


1 Answers

Change your select to:

.Select((s, i) => (i+1) + "-" + s.name)

This overload of the Select method will pass in the index as the second parameter to the lambda expression.

like image 165
StriplingWarrior Avatar answered Dec 21 '22 11:12

StriplingWarrior