使用 lambda 中包含的匿名类型定义 lambda 表达式
我试图避免在 lambda 表达式中使用动态类型来对集合进行分组。该类型是在编译时匿名定义的(据我所知是明确定义的)。我不想将该类型定义为成熟的类,因为我只在这个方法中使用它几次。
示例代码:
Func<MyData, dynamic> dataGrouping = md => new
{
md.Property1,
md.Property2,
md.Property3
};
var groupedData = myDataCollection.GroupBy(dataGrouping);
虽然这可以编译,但由于类型是动态的,因此组内没有智能感知或强类型。
我无法将 dataGrouping 的类型指定为 var,因为我使用的是 C#,而且我收到了这样的抱怨:无法将 lambda 表达式分配给隐式类型化局部变量。
我可以用匿名类型上的 GetType() 的结果替换dynamic吗?然后,在 lambda 中使用该类型之前,我需要该类型,但在进入 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否有任何理由不想将 lambda 表达式直接放入
GroupBy
调用中?这就是它们通常结合在一起的方式:您可以使用额外的方法来完成此工作:
然后使用类型推断:
请注意我如何显式键入参数,以便类型推断可以使用。这会起作用,但有点难看。我会将 lambda 表达式直接嵌入到方法调用中,除非您有任何特殊原因不这样做。
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:You could make this work with an extra method:
and then use type inference:
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.