The
group by clause returns a sequence of objects that contain zero or more
items that match the key value for the group. In this example we have
show to you how to use group by query syntaxand lambda expression in
mvc application.
public ActionResult AggregateFunction()
{
List<Employee> EmployeeCollection = new List<Employee>();
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 });
//simple query
var queryLastNames = from employee in EmployeeCollection
group employee by employee.Name into newGroup
select new GroupByClause { EmpName = newGroup.Key, salary = newGroup.Sum(x => x.Salary) };
//lambda expression query
var EmployeeScoring = EmployeeCollection.Where(x => (x.IsActive == true)).GroupBy(k => k.Name).
Select(p => new GroupByClause
{
EmpName = p.Key,
salary = p.Sum(x => x.Salary)
});
}
In view cshtml page
<ul>
@foreach (var item in ViewBag.EmployeeScoring as List<GroupByClause>)
{
<li><span>@Html.Raw(item.EmpName) </span> <span>@item.salary</span> </li>
}
No comments:
Post a Comment