C#林克加入查询
本文关键字:查询 林克 | 更新日期: 2023-09-27 17:57:37
我正在尝试创建一个查询,将ID和StudentID字段中的Student和Enrolled数据连接起来,这样我就可以只显示在History中注册的学生的姓名,因为Steve Thomas的ID是3,History所需的StudentID也是。
我的另一个查询(IEnumerable学生查询)只访问了学生数据,没有注册。因此,我不确定如何将两者结合在一起。我会使用多个from吗?
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public DateTime DateOfBirth { get; set; }
}
class Enrolled
{
public int StudentID { get; set; }
public string CourseName { get; set; }
}
IEnumerable<Student> students = new List<Student>()
{
new Student {FirstName = "Jim", LastName = "Smith", DateOfBirth = new DateTime(1990, 5, 21), ID = 1},
new Student {FirstName = "Diane", LastName = "Sawyer", DateOfBirth = new DateTime(1992, 11, 1), ID = 2},
new Student {FirstName = "Steve", LastName = "Thomas", DateOfBirth = new DateTime(1994, 4, 4), ID = 3},
new Student {FirstName = "Pablo", LastName = "Dicaz", DateOfBirth = new DateTime(1973, 3, 30), ID = 4},
new Student {FirstName = "Hannu", LastName = "Korppi", DateOfBirth = new DateTime(1988, 6, 16), ID = 5},
new Student {FirstName = "Marie", LastName = "St. Claude", DateOfBirth = new DateTime(1982, 1, 19), ID = 6}
};
var enrolllist = new List<Enrolled>
{
new Enrolled {CourseName = "Computer Science",StudentID = 2},
new Enrolled {CourseName = "Computer Science",StudentID = 5},
new Enrolled {CourseName = "History",StudentID = 1},
new Enrolled {CourseName = "Psychology",StudentID = 2},
new Enrolled {CourseName = "History",StudentID = 4},
new Enrolled {CourseName = "Computer Science",StudentID = 3},
new Enrolled {CourseName = "Psychology",StudentID = 6},
new Enrolled {CourseName = "History",StudentID = 3},
};
IEnumerable<Student> query = from s in students
where s.DateOfBirth.Year < 1990
orderby s.FirstName
select s;
foreach (Student stud in query)
{
Console.WriteLine(stud.FirstName);
Console.ReadLine();
}
您可以连接这两个集合,类似于在SQL
查询中连接两个表的方式。
var query = (from s in students
join e in enrolllist on s.ID equals e.StudentID
where e.CourseName == "History"
select s)
students.ID
字段与enrolled.StudentID
字段连接。
您可以在这里和这里阅读更多关于join
如何工作的信息。