Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Sample LINQ with Multiple Joins and Selected Columns

4.58/5 (8 votes)
1 Jun 2020CPOL 29.4K  
How to write a LINQ statement with multiple joins
In this post, we will go through a sample that shows how to write a LINQ statement with multiple joins.

If you are like me, I sometimes find it difficult to remember the syntax of LINQ statements because I jump from T-SQL to ASP.NET and C#.

I was searching for a sample that may show how to write a LINQ statement with multiple joins and I had little luck finding it, so finally, after I put my few brain cells in action, I came up with the following:

C#
var dbRegCourses = (from a in db.CourseRegistries
                    join b in db.Courses on a.courseid equals b.id
                    join c in db.aspnet_Users on a.userid equals c.UserId
                    where a.userid == sUserID
                    orderby a.regdate, b.code, b.description,
                            b.instructor, b.date, b.venue
                    select new
                    {
                      a.regdate, b.code, b.description,
                      b.instructor, b.date, b.venue});

if (dbRegCourses.Count() > 0)
{
    ResultLbl.Text = "We found that you are registered to: " +     
                      dbRegCourses.Count().ToString() + " Courses.";
    return;
}

If you notice, here we are joining three tables, using a where statement and then picking and choosing columns from at least two tables.

I also added an if statement bottom to see if I got any rows back from the LINQ Statement and if that's the case, return a message.

Hope this helps somebody out there,
Will

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)