2010-07-19 55 views
6

我一直在使用101 LINQ Samples让我的脚使用LINQ湿。这是一个很好的第一资源,但我看不到我目前需要的一个例子。组号的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。怎么样?

回答

9

这要看您的具体需求,但你可以使用:

var groupArray = groups.ToArray(); 

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


如果你需要创建对象的指数,另一种选择是使用Select

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

嘿,聪明。我喜欢。 – 2010-07-19 17:17:06

+0

+1 ... clever =) – Luiscencio 2010-07-19 17:18:23

+0

这里有两个答案。我喜欢ToList解决方案,但两个参数选择正是我所期待的。非常感谢。 – 2010-07-19 17:46:24

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

+1用于关联GroupNumber和LINQ结果。 – 2010-07-19 17:40:24

1

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

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

+0

像我的原始解决方案,但更清洁,增量不会在处理代码中丢失。 – 2010-07-19 17:51:18