A rather cryptic (but short) way would be:
int w = 5; // window size
var list = new List<int> { 0, 1, 2, 3, 4, 5, 12, 15, 16, 22,
23, 24, 26, 27, 28, 29 };
var result = list.Select(x => list.Where(y => y >= x - w && y <= x + w))
.Aggregate((a, b) => (a.Count() > b.Count()) ? a : b);
Console.WriteLine(string.Join(",", result.ToArray()));
Prints
22,23,24,26,27,28,29
This code consists of 3 steps:
- For a given
x
the snippetlist.Where(y => y >= x - w && y <= x + w)
gives all elements from the list that are in the cluster aroundx
. list.Select(x => ...)
computes that cluster for every element of the list..Aggregate((a, b) => (a.Count() > b.Count()) ? a : b)
takes the cluster of maximum size.