Set values with a Linq-Query?
14,378
Solution 1
Might this work?
int rankPosition = 1;
var sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => {
r.MesaAdvertNumber = ++rankPosition;
return r;
});
Solution 2
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.
Related videos on Youtube
Author by
TalkingCode
Updated on April 28, 2022Comments
-
TalkingCode almost 2 years
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?
-
Martin Jonáš over 14 yearsIt 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.