获得最后x连续项与LINQ [英] Getting last x consecutive items with LINQ
问题描述
我的问题是类似这样的:<一href="http://stackoverflow.com/questions/7112435/finding-consecutive-items-in-list-using-linq">Finding使用LINQ 在列表连续项。除了,我想获得有没有间隙,最后连续项。例如:
My question is similar to this one: Finding Consecutive Items in List using Linq. Except, I'd like to get the last consecutive items that have no gaps. For example:
2, 4, 7, 8
输出
7,8
另外一个例子:
Another example:
4,5,8,10,11,12
输出
10,11,12
那怎么可以呢?
How can that be done?
推荐答案
我假设在您需要的最后一个连续序列多个成员......所以从顺序
I'm assuming in that you want the last consecutive sequence with more than one member... so from the sequence
{4, 5, 8, 10, 11, 12, 15}
你期待的顺序:
you're expecting the sequence:
{10, 11, 12}
我所示的线以除去如果最后序列允许仅具有单个构件,给人的序列
I've indicated the line to remove if the last sequence is permitted to have only a single member, giving a sequence of
{15}
这里的LINQ:
Here's the linq:
new[] {4, 5, 8, 10, 11, 12, 15}
.Select((n,i) => new {n, i})
.GroupBy(x => x.n - x.i) //this line will group consecutive nums in the seq
.Where(g => g.Count() > 1) //remove this line if the seq {15} is expected
.Select(x => x.Select(xx => xx.n))
.LastOrDefault()
有一个隐含的假设,这里说的序列号是按升序排列。如果不是这种情况,就必须报名参加微软的扩展方法的权力为发现相邻项在一个序列。让我知道如果是这样的话。
There's a hidden assumption here that the numbers of the sequence are in ascending order. If this isn't the case, it will be necessary to enroll the powers of microsoft's extension method for finding contiguous items in a sequence. Let me know if this is the case.
这篇关于获得最后x连续项与LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!