LINQ(Language Integrated Query)是一种查询语言集成技术,用于对各种数据源进行统一的查询和操作。它是C#语言中的一个强大功能,提供了一种直观且表达力强的方式来查询和操作数据,包括集合、数据库、XML等。
// 查询名字以"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 关键字选择这些名字。
// 查询名字长度大于3的学生
List<string> names = new List<string> { "Alice", "Bob", "Adam", "Amy" };
var query = names.Where(name => name.Length > 3);
foreach (var name in query)
{
Console.WriteLine(name); // 输出: Alice, Adam
}
在以上示例中,LINQ方法语法使用 Where 方法来筛选名字长度大于3的学生名字。
// 查询年龄大于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
select student.Name;
foreach (var name in query)
{
Console.WriteLine(name); // 输出: Alice, Adam, Amy
}
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
在以上示例中,LINQ查询从学生对象集合中筛选出年龄大于18的学生的名字。
// 使用LINQ to SQL查询数据库
using (var context = new MyDbContext())
{
var query = from product in context.Products
where product.Price > 50
select product.Name;
foreach (var name in query)
{
Console.WriteLine(name);
}
}
在以上示例中,通过LINQ to SQL查询数据库中价格大于50的产品的名称。
// 对学生按年龄进行排序
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
orderby student.Age
select student.Name;
foreach (var name in query)
{
Console.WriteLine(name); // 输出: Bob, Amy, Alice, Adam
}
// 使用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
}
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int DepartmentId { get; set; }
}
class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
在以上示例中,使用 OrderBy 对学生按年龄进行排序,使用 Join 连接学生和部门数据源,并选择学生的姓名和部门名称进行输出。