C#中的LINQ(Language Integrated Query)方法语法是使用方法调用链(Method Chaining)的方式来进行查询操作,它使用扩展方法和Lambda表达式来实现查询和操作数据。
// 查询名字以"A"开头的学生
List<string> names = new List<string> { "Alice", "Bob", "Adam", "Amy" };
var query = names.Where(name => name.StartsWith("A"))
.Select(name => name);
foreach (var name in query)
{
Console.WriteLine(name); // 输出: Alice, Adam, Amy
}
在以上示例中,LINQ方法语法从names列表中筛选出以字母"A"开头的名字,并使用Select方法选择这些名字。
// 使用Join连接学生和部门数据源
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Age = 20, DepartmentId = 1 },
new Student { Name = "Bob", Age = 17, DepartmentId = 2 },
new Student { Name = "Adam", Age = 22, DepartmentId = 1 },
new Student { Name = "Amy", Age = 19, DepartmentId = 2 }
};
List<Department> departments = new List<Department>
{
new Department { Id = 1, Name = "Mathematics" },
new Department { Id = 2, Name = "Physics" }
};
var query = students.Join(departments,
student => student.DepartmentId,
department => department.Id,
(student, department) => new { student.Name, department.Name });
foreach (var result in query)
{
Console.WriteLine($"Name: {result.Name}, Department: {result.Name}"); // 输出: Alice - Mathematics, Bob - Physics, Adam - Mathematics, Amy - Physics
}
在以上示例中,使用Join方法连接学生和部门数据源,并指定连接条件和选择结果。
// 查询年龄大于18的学生,并按年龄降序排序
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Age = 20 },
new Student { Name = "Bob", Age = 17 },
new Student { Name = "Adam", Age = 22 },
new Student { Name = "Amy", Age = 19 }
};
var query = students.Where(student => student.Age > 18)
.OrderByDescending(student => student.Age)
.Select(student => student.Name);
foreach (var name in query)
{
Console.WriteLine(name); // 输出: Adam, Alice, Amy
}
在以上示例中,使用Where方法筛选年龄大于18的学生,使用OrderByDescending方法按年龄降序排序,并使用Select方法选择学生的姓名。
// 根据年龄分组学生
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Age = 20 },
new Student { Name = "Bob", Age = 17 },
new Student { Name = "Adam", Age = 20 },
new Student { Name = "Amy", Age = 19 }
};
var query = students.GroupBy(student => student.Age);
foreach (var group in query)
{
Console.WriteLine($"Age: {group.Key}");
foreach (var student in group)
{
Console.WriteLine($"Name: {student.Name}");
}
Console.WriteLine();
}
在以上示例中,使用GroupBy方法根据学生的年龄对结果进行分组,并遍历每个分组输出学生的姓名。