8

In my application I have a list of items I need to sort by price and set a rank/position index for each item. I need to store the rank because the price may change afterward. At the moment I am doing it like this:

var sortedlistKFZ = from res in listKFZ orderby res.Price select res; if (sortedlistKFZ.Any()) { int rankPosition = 1; foreach (Result kfz in sortedlistKFZ) { kfz.MesaAdvertNumber = rankPosition; rankPosition++; } } 

Is there a shorter way to do it?

3 Answers 3

9

Might this work?

int rankPosition = 1; var sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => { r.MesaAdvertNumber = ++rankPosition; return r; }); 
Sign up to request clarification or add additional context in comments.

1 Comment

It will, except for one small detail ... the numbering will start from 2. You need change increment to postfix (rankPosition++) or initial value of rankPosition to 0.
3

You could do it using the let keyword. This should work...

Int32[] numbers = new Int32[] { 3, 6, 4, 7, 2, 8, 9, 1, 2, 9, 4 }; int count = 1; var ranked = from n in numbers let x = count++ select new { Rank = x, Number = n }; 

Comments

1

The simplest one would be

(from res in listKFZ orderby res.Price select res).ToList().ForEach(...) 

Of course you can write your own ForEach extension for IEnumerable but I remember I had side-effect with it. It's better to operate on List.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.