簡體   English   中英

可以在LINQ中按Count分組嗎?

[英]Possible to group by Count in LINQ?

這可能是不可能的,也可能是顯而易見的。

我有一個對象列表(讓我們說這個例子的整數):

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

我希望能夠成對分組而不考慮順序或任何其他比較,返回一個新的IGrouping對象。

list.GroupBy(i => someLogicToProductPairs);

我可能正在從錯誤的角度處理這個問題,但目標是通過恆定的容量對一組對象進行分組。 任何幫助是極大的贊賞。

你的意思是這樣的:

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

產量

1, 2
3, 4
5, 6

你可以這樣做......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM