views:

88

answers:

1

LINQ-newb having trouble using grouping. I'm trying to query an IEnumerable called dosesWithHighestScore.

I'm following this example: http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#minGrouped

Here's my code:

    var doseWithLowestVolumeForForm =
        from d in dosesWithHighestScore
        group d by d.formulation.form into g                
        select new { 
            Form = g.Key, 
            LowDose = g.Group.Min(d => d.doseAdministrableAmount)
        };

The use of "Group" is causing this error:

'System.Linq.IGrouping' does not contain a definition for 'Group' and no extension method 'Group' accepting a first argument of type 'System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)

Here are my usings:

using System;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;

Why am I getting this error?

+1  A: 

You an get rid of the Group term in your assignment to LowDose. In LINQ-to-objects, a group is itself an IEnumerable<>, so you can apply other LINQ operations to it without any additional qualifiers. The Key property is provided on IGrouping so that you can access the value by which the group was ... well, grouped.

var doseWithLowestVolumeForForm =
        from d in dosesWithHighestScore
        group d by d.formulation.form into g                
        select new { 
            Form = g.Key, 
            LowDose = g.Min(d => d.doseAdministrableAmount)
        };

The examples on the site that show the use of a Group property are incorrect.

LBushkin
That compiles - thanks! So, one more follow-up question: how do I access the results? I thought I would be able to do something like dosesWithLowestVolumeForForm[0].Form but that's not working.
Marvin
The result of a LINQ statement is a query object ... not an array. There are different ways of accessing the results - depending on what you want to do with them. A common way is to use a `foreach` loop to evaluate each result; as in: `foreach( var item in doseWithLowestVolumeForForm ) { ... }`. Alternatively, if you are only interested in the first result, you can do: `doseWithLowestVolumeForForm.First()` which will return the first result in the query. Other alternatives exist too... but, again, it depends on what you need to do with the results.
LBushkin