我有以下查询,该查询采用DataTable
并计算值在countField
列中显示的次数。
var countField = "class"
var query = from row in myDataTable.AsEnumerable()
group row by row.Field<string>(countField)
into sumry
orderby sumry.Count() descending
select new
{
Text = sumry.Key,
CountofRows = sumry.Count()
};
除非该列包含十进制值,否则它将按预期工作。我对linq
不熟悉,知道要改变什么以允许它计算小数值的实例。
如何使此语句更加健壮,以便它适用于指定列中包含的任何数据类型?
答案 0 :(得分:3)
您可以使用DataRow's
索引器获取值并将其转换为string
:
var query = from row in myDataTable.AsEnumerable()
group row by row[countField].ToString()
into sumry
orderby sumry.Count() descending
select new
{
Text = sumry.Key,
CountofRows = sumry.Count()
};
这应该适用于所有类型。
答案 1 :(得分:1)
您可以获取列的类型并使用反射来调用Field<T>()
。 (请参阅此答案以调用通用方法:https://stackoverflow.com/a/232621/409259)
var columnType = myDataTable.Columns[countField].DataType;
var method = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(string) });
var generic = method.MakeGenericMethod(columnType);
var query = from row in myDataTable.AsEnumerable()
group row by generic.Invoke(null, new object[] { row, countField })
into sumry
orderby sumry.Count() descending
select new
{
Text = sumry.Key,
CountOfRows = sumry.Count()
};