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.

Share:
14,378

Related videos on Youtube

TalkingCode
Author by

TalkingCode

Updated on April 28, 2022

Comments

  • TalkingCode
    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áš
    Martin Jonáš over 14 years
    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.