Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group neighboring values using linq

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.

like image 866
Alex Blokha Avatar asked Oct 20 '22 21:10

Alex Blokha


2 Answers

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;
        });
}

enter image description here

like image 80
PiotrWolkowski Avatar answered Oct 31 '22 14:10

PiotrWolkowski


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; 
});
like image 37
Ben Reich Avatar answered Oct 31 '22 14:10

Ben Reich