Reputation: 7722
Say I have the following class:
internal class ModuleScrap
{
public System.DateTime ReadTime { get; set; }
public int NetScrap { get; set; }
}
I would like a Linq query that finds for me all NetScrap values that were greater than the NetScrap value before it, based on ReadTime. So, a query that looks something like this:
MyList
.OrderBy(row => row.ReadTime)
.Where (row => row.NetScrap > [The Previous NetScrap Value])
Is such a query possible?
Upvotes: 1
Views: 290
Reputation: 1503270
Yes, using Zip
and Skip
(assuming .NET 4):
// Avoid having to do the ordering twice
var ordered = list.OrderBy(row => row.ReadTime).ToList();
var greater = ordered.Zip(ordered.Skip(1), (x, y) => new { x, y })
.Where(p => p.y.NetScrap > p.x.NetScrap)
.Select(p => p.y);
Zipping a sequence with itself skipped one gives you pairs of consecutive elements:
Original a b c d e f
Original.Skip(1) b c d e f g
If you read each column from the above, you get the pairings. From there, you just need to select each value where the second entry's NetScrap
is greater than the first.
Upvotes: 6