Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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, IEnumberable<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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading