Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain pairs in a list with LINQ

Tags:

c#

linq

I have a list, for example, {1, 2, 3, 4, 5}

I need to get pairs of it (using C# LINQ):

(1, 2), (2, 3), (3, 4), (4, 5)

Strangely, I can't solve this simple task, though I tried SelectMany with Skip(i + 1), which gives me all possible pairs, that I basically don't need.

like image 798
perceptr Avatar asked Jan 25 '26 13:01

perceptr


2 Answers

You could do this with Linq Zip method:

var numbers = new[] { 1, 2, 3, 4, 5 };

var pairs = numbers.Zip(numbers.Skip(1));

foreach (var pair in pairs)
{
    Console.WriteLine($"First: {pair.First}, Second: {pair.Second}");
}

Output:

First: 1, Second: 2
First: 2, Second: 3
First: 3, Second: 4
First: 4, Second: 5

Running example: https://dotnetfiddle.net/HZuDdR

like image 155
DavidG Avatar answered Jan 28 '26 02:01

DavidG


using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var list = new List<int>{1, 2, 3, 4, 5};
        var pairs = list.Take(list.Count() - 1).Select((z, index) => new
        {
            a = z, b = list[index + 1]
        }).ToList();
        pairs.ForEach(p => Console.Write("(" + p.a + "," + p.b + ") "));
    }
}

https://dotnetfiddle.net/6oXQwC

like image 45
Johan Nordlinder Avatar answered Jan 28 '26 04:01

Johan Nordlinder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!