LINQ的方法来收集组分为多个子群的元素的指定数量子群、多个、组分、方法来

2023-09-07 04:37:18 作者:小时候的裸奔是那么潇洒°

是否有一个给定的集合存在的LINQ方法分组为子组的元素我的意思是指定数量,像Scala的组合方法。 例如在Scala中,名单(89,67,34,11,34).grouped(2)名单(名单(89,67),列表(34,11),表(34))

Does there exist a LINQ method to group a given collection into subgroups with specified number of elements I mean, something like Scala's grouped method. e.g. in Scala, List(89, 67, 34, 11, 34).grouped(2) gives List(List(89, 67), List(34, 11), List(34)).

在这种情况下,一个方法不存在,这将是LINQ办法做到这一点?

In case such a method doesn't exist, what would be the LINQ way to do it?

推荐答案

是的,你可以。但是你可以争辩说,如果这是非常pretty的...

Yes, you can. But you can argue if it's very pretty...

  Int64[] aValues = new Int64[] { 1, 2, 3, 4, 5, 6 };
  var result = aValues
          .Select( ( x, y ) => new KeyValuePair<Int64, Int32>( x, y ) )
          .GroupBy( x => x.Value / 2 )
          .Select( x => x.Select( y => y.Key ).ToList() ).ToList();

它是如何工作的:

How it works:

选择 X 和是从原来的集合,其中的 X 是实际值和是与首页它的特定收藏。然后点击组由索引和所需的分组长度的整数等分(在本例中的 2 )。

Select x and y from the original collection, where x is the actual value and y is the index of it in the given collection. Then group by integer devision of the index and the desired grouping length ( in this example 2 ).

由整数等分分组会总结到下 - 这样 0/2 = 0 1 / = 0 等,这将给我们所需要的分组类别值。这就是我们在分组对抗在这里。

Grouping by integer devision will round up to the lower - so 0 / 2 = 0, 1 / 2 = 0, etc. which will give us the needed grouping category value. This is what we are grouping against here.

有关结果只选择分组列表中的值,并将其返回为表的集合。

For result select only the values grouped in lists and return them as a collection of lists.