C# Datatable: Computing the average in a column

kknaguib picture kknaguib · Feb 25, 2014 · Viewed 16.2k times · Source

I'm trying to get the average P&L in a column. The column is of type double, however I keep getting an error saying the following:

Additional information: Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.

This occurs when this line is executing:

avgFiveSbefore = (double)dt.Compute("AVG(5sBeforePnL)", "");

Also, here's some additional code to clarify:

dt.Columns.Add(Columns.FiveSecBeforePnL, typeof(double));

foreach(DataRow row in dt.Rows)
{
  row[Columns.FiveSecBeforePnL] = some value;
}

double avgFiveSbefore;
avgFiveSbefore = (double)dt.Compute("AVG(5sBeforePnL)", "");

Answer

Habib picture Habib · Feb 25, 2014

Try enclosing the column name in square brackets.

avgFiveSbefore = (double)dt.Compute("AVG([5sBeforePnL])", "");

You can also use LINQ to do the same like:

double avgFiveSbefore = dt.AsEnumerable()
                            .Average(r =>
                                r.Field<double>(Columns.FiveSecBeforePnL));