c# - LINQ Group by Query 中的组号

标签 c# linq group-by

我一直在使用 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。怎么办?

最佳答案

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

var groupArray = groups.ToArray();

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


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

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

关于c# - LINQ Group by Query 中的组号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3283251/

相关文章:

c# - |x-y|之间差值最小的改进方程算法ax+by=c

linq - 从多个版本项目中选择最新项目的 LINQ 是什么?

c# - 为什么 linq 不实现完全懒惰?

mysql - 查询小调查做基准测试

group-by - clickhouse 下采样到 OHLC 时间条间隔

c# - Blazor WebAssembly : Multiple route on same component rendering

c# - 在 PHP 中显示包含重复列的表格

c# - 将自定义 WSDL 绑定(bind)到现有 WCF 服务

c# - 如何通过 LINQ 比较没有时间的 DateTime?

sql - CakePHP和SQL Server 2008,分组依据不起作用