tags:

views:

61

answers:

3

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?

A: 

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.

queen3
+1  A: 

Might this work?

int rankPosition = 1;
var sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => {
    r.MesaAdvertNumber = ++rankPosition;
    return r;
});
David Hedlund
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.
Matajon
d'oh. that's right of course
David Hedlund
+2  A: 

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
    };
Chalkey