0

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)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Does this answer your question? [Getting pair-set using LINQ](https://stackoverflow.com/questions/1624341/getting-pair-set-using-linq), then get every other result. – gunr2171 Apr 01 '22 at 17:30
  • You can also use an overload of select to use the index of the property and then group by that index into the number of "items per pair" which works for this answer. but not the "duplicate" – Austin Arnett Apr 01 '22 at 17:53

1 Answers1

4

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

IEnumerable<string[]> groups = list.Chunk(2);
Hank
  • 1,976
  • 10
  • 15
  • 2
    //NET framework var zipped = list.Where((_, i) => i % 2 == 0).Zip( list.Where((_, i) => i % 2 == 1), (a, b) => Tuple.Create(a, b)); – Fruchtzwerg Apr 01 '22 at 17:48
  • could you ellaborate a little more how this linq work? I noticed that is missing a parameter in a lambda expression, but still.. I could use some more information – Leandro Manes Apr 04 '22 at 11:31