Home > Back-end >  Chain pairs in a list with LINQ
Chain pairs in a list with LINQ

Time:04-10

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related