LINQ(Language Integrated Query)是.NET框架中一种强大的查询语言,它允许开发者以声明式的方式查询数据。GroupBy是LINQ中一种非常有用的操作,它能够根据一个或多个键将数据分组。本文将通过一个实际的例子,展示如何使用LINQ的GroupBy方法来处理员工数据。
假设有一个员工列表,需要根据不同的属性对员工进行分组。以下是一些常见的分组需求:
首先,需要创建一个员工列表,并添加一些示例数据。
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 1, FName = "John", MName = "", LName = "Shields", DOB = DateTime.Parse("12/11/1971"), Sex = 'M' });
empList.Add(new Employee() { ID = 2, FName = "Mary", MName = "Matthew", LName = "Jacobs", DOB = DateTime.Parse("01/17/1961"), Sex = 'F' });
// ... 更多员工数据
要实现根据员工名字的首字母进行分组,可以使用以下LINQ查询:
var grpOrderedFirstLetter = empList.GroupBy(employees => new String(employees.FName[0], 1)).OrderBy(employees => employees.Key.ToString());
foreach (var employee in grpOrderedFirstLetter)
{
Console.WriteLine("\n'Employees having First Letter {0}':", employee.Key.ToString());
foreach (var empl in employee)
{
Console.WriteLine(empl.FName);
}
}
要实现根据员工出生年份进行分组,可以使用以下LINQ查询:
var grpOrderedYr = empList.GroupBy(employees => employees.DOB.Year).OrderBy(employees => employees.Key);
foreach (var employee in grpOrderedYr)
{
Console.WriteLine("\nEmployees Born In the Year " + employee.Key);
foreach (var empl in employee)
{
Console.WriteLine("{0,2} {1,7}", empl.ID, empl.FName);
}
}
要实现根据员工出生年月进行分组,可以使用以下LINQ查询:
var grpOrderedYrMon = empList.GroupBy(employees => new DateTime(employees.DOB.Year, employees.DOB.Month, 1)).OrderBy(employees => employees.Key);
foreach (var employee in grpOrderedYrMon)
{
Console.WriteLine("\nEmployees Born in Year {0} - Month {1} is/are :", employee.Key.Year, employee.Key.Month);
foreach (var empl in employee)
{
Console.WriteLine("{0}: {1}", empl.ID, empl.FName);
}
}
要统计同一年出生的员工数量,可以使用以下LINQ查询:
var grpCountYrMon = empList.GroupBy(employees => employees.DOB.Year)
.Select(lst => new { Year = lst.Key, Count = lst.Count() });
foreach (var employee in grpCountYrMon)
{
Console.WriteLine("\n{0} were born in {1}", employee.Count, employee.Year);
}
var ratioSex = empList.GroupBy(ra => ra.Sex)
.Select(emp => new { Sex = emp.Key, Ratio = (emp.Count() * 100) / empList.Count });
foreach (var ratio in ratioSex)
{
Console.WriteLine("\n{0} are {1}%", ratio.Sex, ratio.Ratio);
}