Aggregate
functions perform a calculation on a set of values and return a single
value. Except for COUNT, aggregate functions ignore null values.
Aggregate functions are frequently used with the GROUP BY clause. Here
is list of aggregate functions
COUNT() - Returns the number of rows
AVG() - Returns the average value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
In
this example we have we have learn how to use these operation in linq
to sql. I have crate mvc web application .here I have created the list
employee and perform aggregate function in linq to sql
In home controller
public ActionResult AggregateFunction()
{
List<Employee> EmployeeCollection = new List<Employee>();
EmployeeCollection.Add(new Employee { id = 1, Name = "Anil Sharma", Address = "India", Salary = 12122, IsActive = true });
EmployeeCollection.Add(new Employee { id = 12, Name = "abc", Address = "Usa", Salary = 12156, IsActive = true });
EmployeeCollection.Add(new Employee { id = 3, Name = "xyzx", Address = "uk", Salary = 12676, IsActive = true });
EmployeeCollection.Add(new Employee { id = 4, Name = "Anil Sharma", Address = "germany", Salary = 45455, IsActive = true });
EmployeeCollection.Add(new Employee { id = 15, Name = "sdfd", Address = "India", Salary = 45467, IsActive = true });
EmployeeCollection.Add(new Employee { id = 25, Name = "gg", Address = "India", Salary = 3445, IsActive = false });
ViewBag.CountAggregateFunction = EmployeeCollection.Count(p => p.IsActive == true);//it return 5 records which status active
ViewBag.AVGAggregateFunction = EmployeeCollection.Average(p => p.Salary);//average of all emplolyee salary
ViewBag.SumAggregateFunction = EmployeeCollection.Sum(p => p.Salary);//sum of all salary of employee
ViewBag.MaxAggregateFunction = EmployeeCollection.Sum(p => p.Salary);//Get maximum salary of employee
ViewBag.MinAggregateFunction = EmployeeCollection.Sum(p => p.Salary);//Get minimum salary of employee
//var MinAggregatFirsteFunction = EmployeeCollection.First(p => p.Salary);//Get minimum salary of employee
return View();
}
In AggregateFunction View
<h2>AggregateFunction</h2>
<div>
<ul>
<li>
count: @ViewBag.CountAggregateFunction
</li>
<li>
avg: @ViewBag.AVGAggregateFunction
</li>
<li>
Sum: @ViewBag.SumAggregateFunction
</li>
<li>
Max: @ViewBag.MaxAggregateFunction
</li>
<li>
Min: @ViewBag.MinAggregateFunction
</li>
</ul>
No comments:
Post a Comment