C#中的LINQ(Language Integrated Query)查询语法提供了一种类似于SQL的语法结构,用于在代码中编写查询表达式。它使得查询数据变得直观和简洁,并提供了一系列的关键字和操作符来进行数据的筛选、排序、投影、分组等操作。
// 查询名字以"A"开头的学生
List<string> names = new List<string> { "Alice", "Bob", "Adam", "Amy" };
var query = from name in names
where name.StartsWith("A")
select 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 = from student in students
join department in departments on student.DepartmentId equals department.Id
select 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关键字连接学生和部门数据源,通过on关键字指定连接条件,并选择学生的姓名和部门名称进行输出。
// 查询年龄大于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 = from student in students
where student.Age > 18
orderby student.Age descending
select student.Name;
foreach (var name in query)
{
Console.WriteLine(name); // 输出: Adam, Alice, Amy
}
在以上示例中,使用where关键字筛选年龄大于18的学生,使用orderby关键字按年龄降序排序,并选择学生的姓名进行输出。
// 根据年龄分组学生
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 = from student in students
group student by student.Age;
foreach (var group in query)
{
Console.WriteLine($"Age: {group.Key}");
foreach (var student in group)
{
Console.WriteLine($"Name: {student.Name}");
}
Console.WriteLine();
}
在以上示例中,使用group by关键字根据学生的年龄对结果进行分组,并在每个分组中输出学生的姓名。