List of running minimum values

Posted by scarle88 on Stack Overflow See other posts from Stack Overflow or by scarle88
Published on 2012-11-24T17:02:55Z Indexed on 2012/11/24 17:03 UTC
Read the original article Hit count: 116

Filed under:
|

Given a sorted list of: new []{1, 2, -1, 3, -2, 1, 1, 2, -1, -3}

I want to be able to iterate over the list and at each element return the smallest value iterated so far. So given the list above the resultant list would look like:

1
1
-1
-1
-2
-2
-2
-2
-2
-3

My rough draft code looks like:

var items = new []{1, 2, -1, 3, -2, 1, 1, 2, -1, -3};

var min = items.First();

var drawdown = items.Select(i =>
{
    if(i < min)
    {
        min = i;
        return i;
    }
    else
    {
        return min;
    }
});

foreach(var i in drawdown)
{
    Console.WriteLine(i);
}

But this is not very elegant. Is there an easier to read (linq?) way of doing this? I looked into Aggregate but it seemed to be the wrong tool. Ultimately the list of items will be very long, in the many thousands. So good performance will be an issue to.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ