开发者

Possible to group by Count in LINQ?

开发者 https://www.devze.com 2022-12-08 17:43 出处:网络
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):

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.


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


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


    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

精彩评论

暂无评论...
验证码 换一张
取 消