0

私は次の2つのクラスを持っています

public class Student
{
    public string Name { get; set; }
    public int SchoolId { get; set; }     
}

public class School
{
    public int SchoolId { get; set; }          
    public IList<Student> Students { get; set; }
}

SchoolIdクラス内に を追加するのは変かもしれませんがStudent、トレースのためにこれを行います。

データベースには、 と を含むテーブルがありStudentsます。StudentNameschoolId

Schoolsこのテーブルからすべてを選択してリストを再構築するにはどうすればよいですか

4

1 に答える 1

2

それはかなり簡単です。GroupByLinq でメソッドを使用するだけです。

var results = db.Students
    .GroupBy(s => s.SchoolId,
             (id, g) => new School() { SchoolId = id, Students = g.ToList() });

または、クエリ構文を使用する場合は、次を使用します。

var results = 
    from s in db.Students
    group s by s.StudentId into g
    select new School()
    {
        SchoolId = g.Key,
        Students = g.ToList()
    };
于 2013-03-14T01:04:45.157 に答える