[英]Linq query - dynamic data types
I have a linq query working nicely to aggregate values from a DataTable. 我有一个linq查询,可以很好地汇总来自DataTable的值。
The idea is that a user can select one of a list of fields, and the linq aggregates data according to the field selected. 想法是用户可以选择字段列表之一,并且linq根据所选字段聚合数据。
p_measure is a string variable denoting the name of a field selected. p_measure是一个字符串变量,表示所选字段的名称。
However, in it's current form, this all only works when the selected field is of data type 'float' in the source table. 但是,以当前形式,这仅在源表中所选字段的数据类型为“ float”时才有效。 If the user selects an 'int' ... then I get a cast exception thrown.
如果用户选择一个'int'...,那么我将抛出强制转换异常。
So the question is, how do i make this code 'dynamic' to handle the varying datatypes ? 所以问题是,如何使此代码“动态”以处理各种数据类型?
// Table for receiving aggregated results
var table = new DataTable();
table.Columns.Add(p_dimension, typeof(String));
table.Columns.Add(p_measure, typeof(Double));
// Query to perform aggregation
DataTable query = (from r in rootDT.AsEnumerable()
group r by new
{
Dimension = r.Field<string>(p_dimension)
} into g
select new
{
Dimension = g.Key.Dimension,
Measure = g.Sum(x => x.Field<double>(p_measure))
}
).Aggregate(table, (dt, r) => dt.Rows.Add(r.Dimension,r.Measure); return dt; });
I can handle the type in the "new DataTable" declaration (line 4): 我可以在“ new DataTable”声明中处理类型(第4行):
table.Columns.Add(p_measure, typeof(Double));
by generating & setting a variable of type Type, thus : 通过生成和设置Type类型的变量,从而:
table.Columns.Add(p_measure, myTypeVariable);
But I am at a loss how to handle this one: 但是我不知如何处理这个问题:
x.Field<double>(p_measure)
Any ideas ?? 有任何想法吗 ??
If you want the result to always be a double
you can use 如果您希望结果始终是
double
,则可以使用
Measure = g.Sum(x => Convert.ToDouble(x[p_measure]))
Then it will only on any numeric type, or string columns whose values can all be parsed to a double
. 那么它将仅适用于任何数字类型或其值都可以解析为
double
字符串列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.