【发布时间】:2014-12-08 14:45:39
【问题描述】:
使用 Net 4.5.1、C#....
使用 IQueryable 我有一个返回字典的 GroupBy 子句。这是通过以下代码完成的:
public static Expression<Func<ChartJoin, Dictionary<string, object>>> GetGroupByDictionary(NameValueCollection fields)
{
var parameter = Expression.Parameter(typeof(ChartJoin));
var addMethod = typeof(Dictionary<string, object>)
.GetMethod(
"Add",
new[] { typeof(string), typeof(object) }
);
var selector = Expression.ListInit(
Expression.New(typeof(Dictionary<string, object>)),
fields.AllKeys.Select(
key => Expression.ElementInit(
addMethod,
Expression.Constant(key),
Expression.Convert(
Chart.getNestedPropertyOrField(parameter, fields[key]), // basically drills down to a nested property (note: static method not shown to save space)
typeof(object)
)
)
)
);
var lambda = Expression.Lambda<Func<ChartJoin, Dictionary<string, object>>>(selector, parameter);
return lambda;
}
然后调用是:
NameValueCollection fields = new NameValueCollection();
fields.Add("Year", "Respondent.currentVisitYear");
fields.Add("Month", "Respondent.currentVisitMonth");
// .... could be more fields
<some IQueryable<ChartJoin>
.GroupBy(
Chart.GetGroupByDictionary(fields).Compile(),
new DictionaryComparer<string, object>()
);
DictionaryComparer 允许唯一性,提供 Equals 和 GetHashCode 实现。我想返回带有 Select 子句的字典。仅尝试选择其中一个 GroupBy 键的简单示例(例如 Select(GetKey("Year").Compile())):
private static Expression<Func<IGrouping<IDictionary<string, object>, ChartJoin>, Dictionary<string, object>>> GetKey(String key)
{
var block = ? /// Need logic to get a the IGrouping.Key property and pull the value
var addMethod = typeof(Dictionary<string, object>)
.GetMethod(
"Add",
new[] { typeof(string), typeof(object) }
);
var selector = Expression.ListInit(
Expression.New(typeof(Dictionary<string, object>)),
Expression.ElementInit(
addMethod,
Expression.Constant(key),
Expression.Convert(
block,
typeof(object)
)
)
);
var lambda = Expression.Lambda<Func<IGrouping<IDictionary<string, object>, ChartJoin>, Dictionary<string, object>>>(selector, parameter);
return lambda;
}
如果有人能让我从上述内容开始(即如何创建块表达式以从 GroupBy.Key 中提取 Dictionary 值),那就太好了。
【问题讨论】:
标签: c# linq iqueryable