代码之家  ›  专栏  ›  技术社区  ›  Alexis Abril

是否可以在LINQ中按计数分组?

  •  3
  • Alexis Abril  · 技术社区  · 16 年前

    这可能是不可能的,也可能是显而易见的,我一直在忽略它。

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

    我希望能够成对分组,而不考虑顺序或任何其他比较,返回一个新的IGrouping对象。

    list.GroupBy(i => someLogicToProductPairs);
    

    3 回复  |  直到 16 年前
        1
  •  5
  •   Guffa    16 年前

    你的意思是这样的:

    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
    
        2
  •  1
  •   Stan R.    16 年前

     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);
    
        3
  •  0
  •   Amy B    16 年前
        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()});