Can I group by account in LINQ?

It may be either impossible or so obvious that I continue to go through it.

I have a list of objects (e.g. ints for this example):

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

I would like to be able to group in pairs without taking into account the order or any other comparison, returning a new IGrouping object.

t

list.GroupBy(i => someLogicToProductPairs);

There is a very real possibility, I can approach this problem from the wrong angle, however, the goal is to group a set of objects with constant power. Any help is appreciated.

+3
source share
3 answers

You mean the following:

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()));
}

Exit

1, 2
3, 4
5, 6
+5
source

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);
+1
source
    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()});
0
source

Source: https://habr.com/ru/post/1720476/


All Articles