Wednesday, May 23, 2012
How to Use Group By in LINQ
When you are familiar with SQL Queries it is just the same way to implement in C# as well.from emp in employees
group emp by emp.Salary into grp
select grp;
The above code indicates that --> based on employee salary group employees into group grp;
Key is the group column value;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQPractice
{
class GroupBy
{
static void Main(string[] args)
{
Listemployees = new List
{
new Employee{EmpId=100,EmpName="sachin",Salary=15000},
new Employee{EmpId=101,EmpName="scott",Salary=12000},
new Employee{EmpId=102,EmpName="rahul",Salary=13000},
new Employee{EmpId=103,EmpName="ilyas",Salary=13000}
};
Console.WriteLine("Group operators:");
var query = from emp in employees
group emp by emp.Salary into grp
select grp;
foreach (var group in query)
{
Console.WriteLine(group.Key);
foreach (var emp in group)
{
Console.WriteLine("{0,-5}{1,-8}{2,-6}",emp.EmpId ,emp.EmpName,emp.Salary);
}
}
Console.ReadLine( );
}
}
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment