CẬP NHẬT: Mặc dù không phải là "truy vấn LINQ" như Patrick chỉ ra trong nhận xét, giải pháp này có thể sử dụng lại, linh hoạt và chung chung.
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);
}
}
}
}
Output:
12,15,17
23,25,27
67,33,13
Để có được nhóm thứ 2, thay đổi:
var consecutiveGroups = numbers.FindConsecutiveGroups((x) => x > 10, 3);
Để:
var consecutiveGroups = numbers.FindConsecutiveGroups((x) => x > 10, 3).Skip(1).Take(1);
UPDATE 2 Sau khi tinh chỉnh này trong pro của chúng tôi sử dụng duction, việc thực hiện sau đây là nhanh hơn nhiều như số lượng các mục trong mảng số phát triển lớn hơn.
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>();
}
}
}
Tuyệt vời! - Cảm ơn rất nhiều. –
Mã đẹp và ấn tượng nhanh, nhưng không phải là truy vấn LINQ. –
@Patrick, về mặt kỹ thuật nó không phải là một "truy vấn LINQ" nhưng nếu bạn loại bỏ việc sử dụng System.Linq; dòng, điều này sẽ không hoạt động, do đó nó là LINQ, không phải dưới dạng truy vấn. Và nó linh hoạt hơn theo cách này. Giải quyết vấn đề theo cách tái sử dụng. – Jim