可以使用外连接(Left Join)来对列表进行 LINQ 查询。下面是一个示例代码:
// 创建一个包含对象的列表
List students = new List
{
new Student { Name = "Alice", Age = 20, CourseId = 1 },
new Student { Name = "Bob", Age = 22, CourseId = 2 },
new Student { Name = "Charlie", Age = 21, CourseId = 3 },
new Student { Name = "David", Age = 23, CourseId = 4 },
new Student { Name = "Eve", Age = 20, CourseId = 5 }
};
List courses = new List
{
new Course { Id = 1, Title = "Math" },
new Course { Id = 2, Title = "Science" },
new Course { Id = 3, Title = "History" },
new Course { Id = 4, Title = "English" }
};
// 使用外连接查询学生和课程列表
var query = from student in students
join course in courses on student.CourseId equals course.Id into studentCourse
from sc in studentCourse.DefaultIfEmpty() // 使用DefaultIfEmpty方法指定外连接
select new
{
StudentName = student.Name,
CourseTitle = sc != null ? sc.Title : "N/A" // 如果没有匹配的课程,则显示 "N/A"
};
// 输出结果
foreach(var result in query)
{
Console.WriteLine($"Student: {result.StudentName}, Course: {result.CourseTitle}");
}
在上面的示例中,我们有两个类 Student
和 Course
,其中 Student
类有一个 CourseId
属性用于关联到 Course
类的 Id
属性。我们通过使用外连接 join
关键字和 into
子句将学生和课程列表进行连接。然后,通过使用 from
子句和 DefaultIfEmpty
方法,我们可以指定外连接。最后,我们使用 select
子句创建一个匿名类型,其中包含学生的姓名和课程的标题。在输出结果时,我们使用了三元运算符来判断是否有匹配的课程,如果没有,则显示 "N/A"。