tags:

views:

81

answers:

3

I am wanting to loop through this list of name value pairs and grab them in groups of 4.

The data would be like:

value1 1
value2 1
value3 1
value4 1
value1 2
value2 2
value3 2
value4 2

and it would group it as 1 list that contains

value1 1
value2 1
value3 1
value4 1

and another list that contains

value1 2
value2 2
value3 2
value4 2

I know this can be done easily with a for loop, but I am wondering if there is a good way to do it with LINQ.

+1  A: 

I think you're looking for GroupBy.

Shane Fulmer
Can you show me an example of it grabbing 4 items?
Kodefoo
Are you grouping by 4 elements at a time, or grouping on the second value in your example?
Shane Fulmer
I am grabbing 4 elements at a time.
Kodefoo
Then I like Jon's answer! :)
Shane Fulmer
+3  A: 

There's nothing built into the framework to do this easily, but MoreLINQ has the Batch method:

IEnumerable<IEnumerable<DataItem>> groups = source.Batch(4);

foreach (IEnumerable<DataItem> group in groups)
{
    foreach (DataItem item in group)
    {
        ...
    }
}
Jon Skeet
hey, just by coincidence I wanted to recommend the same ;-)
Johannes Rudolph
Thank you for the answer. I am going to look into this, but i want to try and stay inside the framework.
Kodefoo
+2  A: 

This will group by every 4 items (a, b, c, d), (e, f, g, h), (i, j)

var abc = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };

var xyz = abc.Select((e, i) => new { Item = e, Grouping = (i / 4) }).GroupBy(e => e.Grouping);
GWB
I also like this answer too.
Kodefoo