开发者

Linq Query - Finding consecutive increasing values

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜