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)...
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.
Python list can contain duplicate elements.
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.
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();
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With