简体   繁体   English

使用字符串的嵌套属性动态构建linq groupby表达式

[英]Build linq groupby expression dynamically with nested property from string

I use nhibernate mapping by code, I want to make this expression dynamicllay (with a nested object) 我通过代码使用nhibernate映射,我想使此表达式动态化(带有嵌套对象)

I have a class event that has a relation many to one with Event state/and I want to grouping by code in the table EventState 我有一个与事件状态有很多关系的类事件/并且我想按表EventState中的代码分组

var grouping = query.GroupBy(x => x.EventState.Code)

It works for me with a simple property, here is my code: 它为我提供了一个简单的属性,这是我的代码:

var arg = Expression.Parameter(type, categoryColumnName);
var bodyy = Expression.Convert(Expression.Property(arg, categoryColumnName), typeof (object));
var lambdaGroupBy = Expression.Lambda<Func<Operation, object>>(bodyy, arg);

var keySelector = lambdaGroupBy.Compile();
var grouping = query.GroupBy(keySelector);
return grouping.Select(a => new PieChartObject { Category = a.Key.ToString(), Value = a.Count().ToString() }).ToList();

But I can't do it with nested object. 但是我不能使用嵌套对象。

GroupBy will partition your query by what you provide as key selector. GroupBy将按您提供的键选择器对查询进行分区。 To determine whether two items in your query have the same key, it uses the default comparer of the given type. 为了确定查询中的两个项目是否具有相同的键,它使用给定类型的默认比较器。 For object, this is uses the Equals and GetHashCode methods which in turn for strings mean that the contents of the strings are identical. 对于对象,这使用EqualsGetHashCode方法,这对于字符串而言意味着字符串的内容是相同的。 If you use a class, by default the reference identity is used, so I think that GroupBy isn't doing anything in your case because the keys you provided are not identical, even though they may have the same values. 如果您使用一个类,则默认情况下使用引用标识,因此我认为GroupBy在您的情况下不做任何事情,因为您提供的键即使它们具有相同的值也不相同。

So there are two valid solutions: You can either override Equals and GetHashCode in your nested object class, or you can provide a custom key comparer to GroupBy, if you want this behavior only for this particular query. 因此,有两个有效的解决方案:您可以在嵌套的对象类中重写Equals和GetHashCode,或者如果只希望对特定查询使用此行为,则可以为GroupBy提供自定义键比较器。 But I guess, as you want to be generic, implementing Equals and GetHashCode would be a better option. 但是我想,正如您希望通用的那样,实现Equals和GetHashCode将是一个更好的选择。 The only exception is of course when you cannot do this, eg because it is a compiler-generated class. 当然,唯一的例外是您无法执行此操作,例如,因为它是编译器生成的类。 In that case, there is few things you can do about that. 在这种情况下,您几乎无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM