I\'m trying to prepare data for a graph using LINQ.
The problem that i cant solve is how to calculate the \"difference to previous.
the result I expect is <
Modification of Jon Skeet's answer to not skip the first item:
public static IEnumerable SelectWithPrev
(this IEnumerable source,
Func projection)
{
using (var iterator = source.GetEnumerator())
{
var isfirst = true;
var previous = default(TSource);
while (iterator.MoveNext())
{
yield return projection(iterator.Current, previous, isfirst);
isfirst = false;
previous = iterator.Current;
}
}
}
A few key differences... passes a third bool parameter to indicate if it is the first element of the enumerable. I also switched the order of the current/previous parameters.
Here's the matching example:
var query = list.SelectWithPrevious((cur, prev, isfirst) =>
new {
ID = cur.ID,
Date = cur.Date,
DateDiff = (isfirst ? cur.Date : cur.Date - prev.Date).Days);
});