I have an integer list that contains about 60-70 elements. How can i get lists that contains 10 integer elements by using linq? If there are 68 elements then function should return 6 lists that contain 10 elements and 1 list that contains 8 elements.
Asked
Active
Viewed 180 times
2 Answers
7
You want the Batch
operation of MoreLinq
:
http://nuget.org/packages/MoreLinq.Source.MoreEnumerable.Batch/
For example:
var batches = myIntegerList.Batch(10);
foreach (var batch in batches)
foreach (int item in batch)
// Do something with item
If you actually need to convert the sequences to List<int>
:
var batches = myIntegerList.Batch(10, batch => batch.ToList());
foreach (var batch in batches) // batch is now a List<int>
foreach (int item in batch)

Matthew Watson
- 104,400
- 10
- 158
- 276
0
int i = 0;
return items.GroupBy(x => i++ % 10);

sanchop22
- 2,729
- 12
- 43
- 66
-
1
-
Firstly, the ordering is changed, but that wasn't one of the requirements. However, for 69 items, this would give 5 groups of 10 and 2 groups of 9 objects, which doesn't match the question's requirements. – René Wolferink Jun 10 '13 at 13:10
-
@sixlettervariables I've never heard that objection before, but it's a good point. @René I guess `/` is needed in place of `%` then. – Rawling Jun 10 '13 at 13:13
-
I agree with rawling - division (casted/truncated) would work here. @sixlettervariables - can you elaborate on the "once per item." Is there something that says that the lambda must be determistic? – b_levitt Jun 10 '13 at 14:16
-
@b_levitt: besides relying on side effects in a lambda, you have no guarantee that [an implementation of `GroupBy`](http://msdn.microsoft.com/en-us/library/bb534501.aspx) does not call `keySelector` more than once per element in `source`. – user7116 Jun 10 '13 at 14:18
-
@user7116 - My hopes would be that if MS required a deterministic expression that they would mention that in the documentation. In any event this would address the problem I think: – b_levitt Jun 10 '13 at 17:27
-
var groups = list.Select(x => new { Grouping = count++ / 10, Value = x }).GroupBy(x => x.Grouping); – b_levitt Jun 10 '13 at 17:32