ISqlModelMapper.Avg<TModel>(string expression, params object[] parameters) Method
.NET Standard 2.x
Computes the average value using the specified SQL expression for the data retrieved according to the criteria specified in a TModel
class.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public object Avg<TModel>(string expression, params object[] parameters);
Type Parameters
TModel
The type of a model class.
Parameters
expression
System.String
A string of SQL expression used to compute the average value.
parameters
System.Object[]
(Optional) One or more values that you want to use as retrieval arguments in the SQL SELECT statement defined in TModel
.
Returns
System.Object
The average value of the retrieved data. Its data type is determined by the return value of the SQL expression.
Remarks
The expression
parameter contains the string of a SQL expression which will be used by the SQL AVG()
function, therefore, the SQL expression string must comply with the SQL conventions, otherwise, exceptions may be thrown.
This method only returns the data of the first column in the first row of the retrieved data, therefore, please avoid using this method when groups are defined in TModel
.
Examples
The following code example demonstrates how to calculate the average budget for all departments.
using Appeon.ApiDoc.Models.School;
using System;
namespace Appeon.ApiDoc.ISqlModelMapperExamples
{
public class AvgExample
{
private SchoolContext _context;
public AvgExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public void Example()
{
var mapper = _context.SqlModelMapper;
// Calculates the average budget for all departments.
decimal averageBudget = (decimal)mapper.Avg<Department>("Budget");
Console.WriteLine("The average budget for all departments is {0}.",
averageBudget.ToString("N0"));
// Loads all records to show budgets.
var depts = mapper.Load<Department>().ToList();
Console.WriteLine();
Console.WriteLine("The budgets for all departments:");
foreach (var dept in depts)
{
Console.WriteLine(dept.Name + " " + dept.Budget.ToString("N0"));
}
/* The code produces the following output:
The average budget for all departments is 230,000.
The budgets for all departments:
Engineering: 350,000
English: 120,000
Economics: 200,000
Mathematics: 250,000
*/
}
}
}
Example Refer To
Model Class: Department
Applies to
.NET Standard
2.x