C#Linq加入查询

时间:2014-04-10 03:20:05

标签: c# linq join

我正在尝试创建一个连接ID和StudentID字段上的学生和注册数据的查询,以便我只显示在历史记录中注册的学生的姓名,这只是史蒂夫托马斯,因为他的ID是3,与历史记录所需的学生ID一样。

我做的其他查询(IEnumerable学生查询)只访问了未注册的学生数据。所以我不确定如何将两者结合在一起。我会使用多个吗?

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();
}

1 个答案:

答案 0 :(得分:1)

您可以加入这两个集合,类似于您在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的工作原理herehere