views:

62

answers:

1

Hi,

I'm trying to avoid a dynamic type in my lambda expression for grouping a collection. The type is defined anonymously at compile time (and unambiguously as far as I can tell). I'd rather not define the type as a full-fledged class as I'm only using it a few times in this single method.

Sample code:

Func<MyData, dynamic> dataGrouping = md => new
    {
        md.Property1,
        md.Property2,
        md.Property3
    };

var groupedData = myDataCollection.GroupBy(dataGrouping);

While this will compile, it leaves me with no intellisense or strong typing inside the group as the type is dynamic.

I can't specify the type of dataGrouping as var, because I'm in C# and I get complaints of Cannot assign lambda expression to implicitly typed local variable.

Could I replace dynamic with the result of GetType() on the anonymous type? I'd then need the type before it's used in the lambda, but I can't see a useful way to get a handle on it before I'm already into the lambda itself.

Is there an elegant way of getting the type of this anonymous class?

+2  A: 

Is there any reason you don't want to put the lambda expression directly in the GroupBy call? That's the way it all usually hangs together:

var groupedData = myDataCollection.GroupBy(md => new
                         {
                             md.Property1,
                             md.Property2,
                             md.Property3
                         });

You could make this work with an extra method:

static Func<TSource, TResult> CreateFunction<TSource, TResult>
    (Func<TSource, TResult> function)
{
    return function;
}

and then use type inference:

var dataGrouping = CreateFunction((MyData md) => new
{
    md.Property1,
    md.Property2,
    md.Property3
});

Note how I've explicitly typed the parameter so that type inference has something to work with. That will work, but it's a bit ugly. I would embed the lambda expression directly in the method call unless you have any particular reason not to.

Jon Skeet
Precisely what I was going to suggest... but you're a step ahead, as usual ;)
Thomas Levesque
Thanks for the response. The reason I don't want to put the lambda directly in the GroupBy is that I intend to use this grouping on several different collections of MyData within this function, and I was trying to define it only once.
Daniel Curtis
@Daniel: Fair enough. In that case, the "extra method" approach should work, even though it's somewhat ugly.
Jon Skeet