How to use aggregate function MAX in c#?
If you want to put some criteria on columns and retrieve values from it, then you can use aggregate functions.
Calculations , computation part is easy with aggregate functions.
I hope it will be useful for you all.
Example:
In this example, ID is the column name in User table.
We will get records whose ID is maximum. Similarly you can use MIN , SUM and many other aggregate functions.
GetConnString() method is used to return the value of ConnectionString which is stored in web.config.
public string GetMaxUserID()
{
string ConnString = GetConnString();
string sqlString = "SELECT MAX(User.ID) FROM [User]";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlString, conn))
{
cmd.CommandType = CommandType.Text;
conn.Open();
if (cmd.ExecuteScalar() != null)
{
object obj = cmd.ExecuteScalar();
conn.Close();
conn.Dispose();
return obj.ToString();
}
else
{
conn.Close();
conn.Dispose();
return string.Empty;
}
}
}
}
public static string GetConnString()
{
return ConfigurationManager.AppSettings["ConnectionString"].ToString();
}