LINQ query fails while counting int
I have the following query that takes DataTable
and counts the number of times a value appears in a column 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()
};
This works as expected if the column contains no decimal values. I am not familiar enough with linq
to know what needs to be changed so that it can count instances of the decimal value.
How can I make this statement more robust so that it works for any data type contained in the specified column?
source to share
You can just get the value using the indexer DataRow's
and convert it to 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()
};
This should work as expected for all types.
source to share
You can get the type of the column and use reflection to call Field<T>()
. (see this answer for calling common methods: fooobar.com/questions/12090 / ... )
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()
};
source to share