在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表達式實現數據連接的方法。