简体   繁体   中英

Simplest LINQ many-to-many solution

If I have a many-to-many relationship between Students and Classes , and I've created a linking table called Students_Classes , what's the simplest way to get a list of classes from a StudentID?

Right now I'm doing the following (which I know is not elegant):

List<Class> classes = new List<Class>();
List<Students_Classes> students_classes = db.Students_Classes.Where(s => s.StudentID == id).ToList();

foreach (var item in students_classes)
{
    classes.Add(item.Class);
}

What you have is actually ok, however, you could do it in one query ie

var classes = (from s in db.Students_Classes
               where s.StudentID == id
               select s.Class).ToList();

or since you appear to prefer Lambda to LINQ

var classes = db.Student_Classes.Where(s => s.StudentID == id)
                                .Select(s => s.Class)
                                .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM