Defining a lambda expression with an anonymous type contained within that lambda

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?


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.

链接地址: http://www.djcxy.com/p/90346.html

上一篇: 为什么一些C#lambda表达式编译为静态方法?

下一篇: 用包含在该lambda中的匿名类型定义lambda表达式