在C#中,使用LINQ(Language Integrated Query)和Lambda表达式可以轻松地实现数据连接
首先,假设我们有两个类,一个是Student
,一个是Teacher
。这两个类分别包含学生和老师的信息。
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int TeacherId { get; set; }
}
public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
}
现在,我们需要创建两个列表来存储学生和老师的数据。
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "Alice", TeacherId = 1 },
new Student { Id = 2, Name = "Bob", TeacherId = 2 },
new Student { Id = 3, Name = "Charlie", TeacherId = 1 }
};
List<Teacher> teachers = new List<Teacher>
{
new Teacher { Id = 1, Name = "Mr. Smith" },
new Teacher { Id = 2, Name = "Mrs. Johnson" }
};
接下来,我们将使用LINQ和Lambda表达式实现数据连接。在这个例子中,我们将根据TeacherId
连接students
和teachers
列表。
using System.Linq;
var joinedData = students.Join(
teachers,
student => student.TeacherId,
teacher => teacher.Id,
(student, teacher) => new
{
StudentName = student.Name,
TeacherName = teacher.Name
});
最后,我们可以遍历joinedData
并输出结果:
foreach (var item in joinedData)
{
Console.WriteLine($"Student: {item.StudentName}, Teacher: {item.TeacherName}");
}
这将输出以下结果:
Student: Alice, Teacher: Mr. Smith
Student: Bob, Teacher: Mrs. Johnson
Student: Charlie, Teacher: Mr. Smith
这就是如何使用C# LINQ和Lambda表达式实现数据连接的方法。