tags:

views:

167

answers:

3

This might be either impossible or so obvious I keep passing over it.

I have a list of objects(let's say ints for this example):

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };

I'd like to be able to group by pairs with no regard to order or any other comparison, returning a new IGrouping object.

ie,

list.GroupBy(i => someLogicToProductPairs);

There's the very real possibility I may be approaching this problem from the wrong angle, however, the goal is to group a set of objects by a constant capacity. Any help is greatly appreciated.

+3  A: 

Do you mean like this:

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };

IEnumerable<IGrouping<int,int>> groups =
   list
   .Select((n, i) => new { Group = i / 2, Value = n })
   .GroupBy(g => g.Group, g => g.Value);

foreach (IGrouping<int, int> group in groups) {
   Console.WriteLine(String.Join(", ", group.Select(n=>n.ToString()).ToArray()));
}

Output

1, 2
3, 4
5, 6
Guffa
cant you let the little guys get some sometimes :D
Stan R.
+1  A: 

you can do something like this...

 List<int> integers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

 var p = integers.Select((x, index) => new { Num = index / 2, Val = x })
                 .GroupBy(y => y.Num);
Stan R.
A: 
    int counter = 0;
    // this function returns the keys for our groups.
    Func<int> keyGenerator =
      () =>
      {
         int keyValue = counter / 2;
         counter += 1;
         return keyValue;
      };

   var groups = list.GroupBy(i => {return keyGenerator()});
David B