按查询查询LINQ组中的组号

时间:2010-07-19 17:10:20

标签: 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。怎么样?

3 个答案:

答案 0 :(得分:9)

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

var groupArray = groups.ToArray();

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


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

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

答案 1 :(得分:6)

这应该可以解决问题:

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++};

答案 2 :(得分:1)

如果它只是一个连续的组号,只需在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