Search code examples
c#linq

How can I pair up two items from a list using linq?


I have a list that looks like this:

List<string> list = new List<string>()
{
  "item1",
  "item2",
  "item3",
  "item4"
 };

I want to group the items in a way that I have them paired up like this:

[("item1", "item2"),("item3", "item4")]

I dont mind what type I have on return, if its a List, an IGrouping, an array, IEnumerable<Tuple>.. I just want them paired up. I've already achieved this with a simple for messing with the indices but I'm wondering if I can do it with linq (what is my actual object of study here)


Solution

  • In .NET 6, you can use LINQ Chunk<TSource>(int size).

    IEnumerable<string[]> groups = list.Chunk(2);