Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take groups of 5 strings from List [duplicate]

Tags:

c#

.net

linq

I have a List<string> and I want to take groups of 5 items from it. There are no keys or anything simple to group by...but it WILL always be a multiple of 5.

e.g.

{"A","16","49","FRED","AD","17","17","17","FRED","8","B","22","22","107","64"}

Take groups of:

"A","16","49","FRED","AD"
"17","17","17","FRED","8"
"B","22","22","107","64"

but I can't work out a simple way to do it!

Pretty sure it can be done with enumeration and Take(5)...

like image 753
BlueChippy Avatar asked Dec 11 '14 10:12

BlueChippy


People also ask

Can you have duplicate values in a list?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.

Can a list have duplicate values in Python?

Python list can contain duplicate elements.

Can we remove duplicate elements of a list how?

To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of the set() method is that it returns distinct elements.


2 Answers

You can use the integer division trick:

List<List<string>> groupsOf5 = list
    .Select((str, index) => new { str, index })
    .GroupBy(x => x.index / 5)
    .Select(g => g.Select(x => x.str).ToList())
    .ToList();
like image 106
Tim Schmelter Avatar answered Sep 20 '22 18:09

Tim Schmelter


 List<List<string>> result = new List<List<string>>();
 for(int i = 0; i < source.Count; i += 5 )
      result.Add(source.Skip(i).Take(5).ToList());

Like this?

like image 28
Florian Schmidinger Avatar answered Sep 19 '22 18:09

Florian Schmidinger