tags:

views:

137

answers:

3

I've been using 101 LINQ Samples to get my feet wet using LINQ. It's been a good first resource, but I can't see an example there of what I currently need.

I just need to associate a sequential group number with each group. I have a working solution:

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

But, I'm sure it's possible to use LINQ to also generate the groupNumber. How?

+5  A: 

this should do the trick:

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++};
Luiscencio
+1 for associating the GroupNumber with the LINQ result.
Dave M
+4  A: 

This depends on your exact needs, but you can use:

var groupArray = groups.ToArray();

Similarly, you can use ToList. These data structures are sequential, and each group has an index.


If you do need the index on the object you create, another option is to use Select:

list.GroupBy(c => c.Name)
    .Select((details, ind) =>
    new
    {
        Name = details.Key,
        DetailRecords = details,
        Index = ind
    });
Kobi
heh, smart. I like it.
BioBuckyBall
+1 ... clever =)
Luiscencio
There are two answers here. I like the ToList solution, but the two parameter select was exactly what I was looking for. Many thanks.
Dave M
No problem. In a way, it means you have an index on any `IEnumerable`, but as I've said, it depends on your needs whether it should be in every object or not. Thanks!
Kobi
+1  A: 

if it's just a sequential group number, just use the Count() method on your 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
}

Then, if you need the specific group number, you can just grab i.

AllenG
Like my original solution, but cleaner in that the increment won't get lost in the processing code.
Dave M