更新:虽然Patrick在评论中指出在技术上并非“linq查询”,但此解决方案可重复使用,灵活且通用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication32
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 6, 4, 10, 9, 12, 15, 17, 8, 3, 20, 21, 2, 23, 25, 27, 5, 67,33, 13, 8, 12, 41, 5 };
var consecutiveGroups = numbers.FindConsecutiveGroups((x) => x > 10, 3);
foreach (var group in consecutiveGroups)
{
Console.WriteLine(String.Join(",", group));
}
}
}
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> FindConsecutiveGroups<T>(this IEnumerable<T> sequence, Predicate<T> predicate, int count)
{
IEnumerable<T> current = sequence;
while (current.Count() > count)
{
IEnumerable<T> window = current.Take(count);
if (window.Where(x => predicate(x)).Count() >= count)
yield return window;
current = current.Skip(1);
}
}
}
}
输出:
12,15,17
23,25,27
67,33,13
要获得第二组,更改:
var consecutiveGroups = numbers.FindConsecutiveGroups((x) => x > 10, 3);
要:
var consecutiveGroups = numbers.FindConsecutiveGroups((x) => x > 10, 3).Skip(1).Take(1);
更新2在我们的职业调整之后由于numbers数组中的项数越来越大,下面的实现要快得多。
public static IEnumerable<IEnumerable<T>> FindConsecutiveGroups<T>(this IEnumerable<T> sequence, Predicate<T> predicate, int sequenceSize)
{
IEnumerable<T> window = Enumerable.Empty<T>();
int count = 0;
foreach (var item in sequence)
{
if (predicate(item))
{
window = window.Concat(Enumerable.Repeat(item, 1));
count++;
if (count == sequenceSize)
{
yield return window;
window = window.Skip(1);
count--;
}
}
else
{
count = 0;
window = Enumerable.Empty<T>();
}
}
}
辉煌! - 非常感谢。 –
漂亮的代码,赫然快,但不是一个LINQ查询。 –
@Patrick,在技术上它不是一个“LINQ查询”,但如果您删除使用System.Linq的;行,这将无法正常工作,因此它是Linq,而不是以查询的形式。而且这样更灵活。以可重复使用的方式解决问题。 – Jim