I have a sorted list of int values, and I want to make groups neighboring values. The values, where next value is nextvalue>= prevValue+1 are neighbors.
For example: List:
{1,2,3,5,6,8,9,10}
Groups will be:
{1,2,3}
{5,6}
{8,9,10}
Could this be done using linq?
This can be easily done without linq - by iterating the list, but I'm wondering if linq has solution for this.
This worked for me:
private static void GroupToNeighboursTest()
{
var numbers = new List<int> { 1, 2, 3, 5, 6, 8, 9, 10 };
var neighbours = numbers
.Zip(numbers.Skip(1), Tuple.Create)
.Aggregate(new List<List<int>> { new List<int> { numbers.First() } }, (result, i) =>
{
if (i.Item1 == i.Item2 - 1)
{
result.Last().Add(i.Item2);
}
else
{
result.Add(new List<int> { });
result.Last().Add(i.Item2);
}
return result;
});
}
If you must use Linq, you could consider the Aggregate
method.
x.Aggregate(new List<List<int>> { new List<int>() }, (soFar, next) => {
if (soFar.Last().Contains(next - 1)) {
soFar.Last().Add(next);
} else {
soFar.Add(new List<int> { next });
}
return soFar;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With