Reputation: 13557
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?
Upvotes: 8
Views: 14880
Reputation:
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
};
Upvotes: 3
Reputation: 129792
Might this work?
int rankPosition = 1;
var sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => {
r.MesaAdvertNumber = ++rankPosition;
return r;
});
Upvotes: 9
Reputation: 15511
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.
Upvotes: 1