I have a list of prices ordered by date. I need to select all monotonously decreasing values. The following code works:
public static List<DataPoint> SelectDecreasingValues(List<DataPoint> dataPoints)
{
var ret = new List<DataPoint>(dataPoints.Count);
var previousPrice = dataPoints[0].Price;
for (int i = 0; i < dataPoints.Count; i++)
{
if (dataPoints[i].Price <= previousPrice)
{
ret.Add(dataPoints[i]);
previousPrice = dataPoints[i].Price;
}
}
return ret;
}
However, is there a shorter/cleaner way to accomplish it with Linq?
This code is equivalent:
However, if you don’t need to have a list, go with plain enumerables and drop the
ToListat the end. That way you can make use of the deferred execution feature built into LINQ.The following code is also equivalent:
This works because of the deferred execution in LINQ. For each item in
dataPointsit will first execute theWherepart and then theSelectpart and only then will it move to the second item indataPoints.You need to decide which version you want to use. The second one is not as intention revealing as the first one, because you need to know about the internal workings of LINQ.