【问题标题】:Group Number in a LINQ Group by QueryLINQ Group by Query 中的组号
【发布时间】:2010-07-19 17:10:20
【问题描述】:

我一直在使用101 LINQ Samples 使用 LINQ 来弄湿我的脚。这是一个很好的第一个资源,但我看不到我目前需要的示例。

我只需要为每个组关联一个连续的组号。我有一个可行的解决方案:

var groups =
   from c in list
   group c by c.Name into details
   select new { Name = details.Key, DetailRecords = details };


int groupNumber = 0;
foreach (var group in groups)
{
   // 
   // process each group and it's records ...
   // 

   groupNumber++;
}

但是,我确信使用 LINQ 也可以生成 groupNumber。怎么样?

【问题讨论】:

    标签: c# linq group-by


    【解决方案1】:

    这取决于您的确切需求,但您可以使用:

    var groupArray = groups.ToArray();
    

    同样,您可以使用ToList。这些数据结构是顺序的,每组都有一个索引。


    如果您确实需要创建对象的索引,另一种选择是使用Select

    list.GroupBy(c => c.Name)
        .Select((details, ind) =>
        new
        {
            Name = details.Key,
            DetailRecords = details,
            Index = ind
        });
    

    【讨论】:

    • 这里有两个答案。我喜欢 ToList 解决方案,但两个参数选择正是我想要的。非常感谢。
    • 没问题。在某种程度上,这意味着您在任何IEnumerable 上都有一个索引,但正如我所说,它是否应该在每个对象中都取决于您的需要。谢谢!
    【解决方案2】:

    这应该可以解决问题:

    int groupNumber = 0;
    var groups =
       from c in list
       group c by c.Name into details
       select new { Name = details.Key, DetailRecords = details, grpNum = groupNumber++};
    

    【讨论】:

      【解决方案3】:

      如果它只是一个连续的组号,只需在您的 IEnumerable 上使用 Count() 方法。

      var groups =
         from c in list
         group c by c.Name into details
         select new {Name = details.Key, DetailRecords = details};
      
      for(int i = 0; i < groups.Count(); i++)
      {
        //Process Records
      }
      

      然后,如果你需要具体的组号,你可以直接抢i

      【讨论】:

      • 和我原来的解决方案一样,但更清晰的是增量不会在处理代码中丢失。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 2016-09-28
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多