LINQ is not very good at things like current amounts, etc. A simple foreach is better here:
static IEnumerable<IEnumerable<int>> GroupByProximity( this IEnumerable<int> source, int threshold) { var g = new List<int>(); foreach (var x in source) { if ((g.Count != 0) && (x > g[0] + threshold)) { yield return g; g = new List<int>(); } g.Add(x); } yield return g; }
Example:
var source = new int[] { 3, 27, 53, 79, 113, 129, 134, 140, 141, 142, 145, 174, 191, 214, 284, 284 }; foreach (var g in source.GroupByProximity(5)) { Console.WriteLine(string.Join(", ", g)); }
Output:
3
27
53
79
113
129, 134
140, 141, 142, 145
174
191
214
284, 284
source share