480

I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the following in LINQ to SQL:

select DealerContact.*
from Dealer 
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
ANeves
  • 6,219
  • 3
  • 39
  • 63
Glenn Slaven
  • 33,720
  • 26
  • 113
  • 165
  • If you have a foreign key between the tables, you should look Kirk Broadhurst's answer below. – Guilherme Nov 20 '16 at 22:35
  • 5
    @ANeves It's far from standard practice to use plural table names, both singular and plural are perfectly acceptable - I just switched from plural to singular myself to match object names - here the top answer agrees singular is more consistent (many pluralisations are weird or non existent - eg '1 sheep, 8 sheep': https://stackoverflow.com/questions/338156/table-naming-dilemma-singular-vs-plural-names/14929526 – niico Jun 11 '18 at 08:47
  • 1
    @niico this is not the place to discuss that, I guess... but Microsoft Entity Framework [pluralizes the table names](https://stackoverflow.com/questions/4425027/entity-framework-code-first-naming-conventions-back-to-plural-table-names), Ruby on Rails' ORM [pluralizes the tables](http://guides.rubyonrails.org/active_record_basics.html#naming-conventions)... is that close enough to standard-practice for you? :) Counter-argument: NHibernate [seems to not pluralize tables](https://github.com/FluentNHibernate/fluent-nhibernate/wiki/Auto-mapping#components). – ANeves Jun 11 '18 at 20:36
  • 2
    Indeed - some people do it one way - some do it another way. There is no standard practice. Personally I think singular has way more benefits. – niico Jun 11 '18 at 20:39

18 Answers18

614

It goes something like:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

It would be nice to have sensible names and fields for your tables for a better example. :)

Update

I think for your query this might be more appropriate:

var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;

Since you are looking for the contacts, not the dealers.

Jon Limjap
  • 94,284
  • 15
  • 101
  • 152
  • 16
    thank you, from now on i will use **sensible names** as best practise which makes sense in linq , instead of `from c or from t1` – Shaiju T Jan 14 '16 at 07:26
  • I've used linq joins like many times in the past but I ran into an issue that I hadn't seen before, since the error you see in VS is not entirely clear: When you write the ON statement you must reference the FROM table first. You can say `on t1.field equals t2.field` but you cannot write `on t2.field equals t1.field` as the compiler won't understand what t2 is referring to in that case. – mvanella Aug 19 '21 at 14:50
249

And because I prefer the expression chain syntax, here is how you do it with that:

var dealerContracts = DealerContact.Join(Dealer, 
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);
CleverPatrick
  • 9,261
  • 5
  • 63
  • 86
  • 13
    If you need to filter or select on fields from *both* joined tables, instead of just on fields of one of the two tables (the DealerContact table in this answer's example), here's an example: http://stackoverflow.com/a/29310640/12484 – Jon Schneider Mar 27 '15 at 21:41
69

To extend the expression chain syntax answer by Clever Human:

If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:

var dealerInfo = DealerContact.Join(Dealer, 
                              dc => dc.DealerId,
                              d => d.DealerId,
                              (dc, d) => new { DealerContact = dc, Dealer = d })
                          .Where(dc_d => dc_d.Dealer.FirstName == "Glenn" 
                              && dc_d.DealerContact.City == "Chicago")
                          .Select(dc_d => new {
                              dc_d.Dealer.DealerID,
                              dc_d.Dealer.FirstName,
                              dc_d.Dealer.LastName,
                              dc_d.DealerContact.City,
                              dc_d.DealerContact.State });

The interesting part is the lambda expression in line 4 of that example:

(dc, d) => new { DealerContact = dc, Dealer = d }

...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.

We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.

Community
  • 1
  • 1
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
47
var results = from c in db.Companies
              join cn in db.Countries on c.CountryID equals cn.ID
              join ct in db.Cities on c.CityID equals ct.ID
              join sect in db.Sectors on c.SectorID equals sect.ID
              where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
              select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };


return results.ToList();
travis
  • 35,751
  • 21
  • 71
  • 94
herste
  • 471
  • 4
  • 2
  • 1
    Hi, Can you tell me please what is this part is about? Status = (ContactStatus)c.StatusID I am interested expecially in the fragment: (ContactStatus)c.StatusID Regards Mariusz – Mariusz Mar 12 '10 at 23:55
  • 1
    @aristo - looking at the code, I'm guessing that `ContactStatus` is really an enum, and `c.StatusID` isn't really an ID, but the numeric value of the enum. If I'm right, `(ContactStatus)c.StatusID` is really just casting an integer to an enum. – Joel Mueller Jul 14 '10 at 22:13
26

Use Linq Join operator:

var q =  from d in Dealer
         join dc in DealerConact on d.DealerID equals dc.DealerID
         select dc;
aku
  • 122,288
  • 32
  • 173
  • 203
26

You create a foreign key, and LINQ-to-SQL creates navigation properties for you. Each Dealer will then have a collection of DealerContacts which you can select, filter, and manipulate.

from contact in dealer.DealerContacts select contact

or

context.Dealers.Select(d => d.DealerContacts)

If you're not using navigation properties, you're missing out one of the main benefits on LINQ-to-SQL - the part that maps the object graph.

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
23

basically LINQ join operator provides no benefit for SQL. I.e. the following query

var r = from dealer in db.Dealers
   from contact in db.DealerContact
   where dealer.DealerID == contact.DealerID
   select dealerContact;

will result in INNER JOIN in SQL

join is useful for IEnumerable<> because it is more efficient:

from contact in db.DealerContact  

clause would be re-executed for every dealer But for IQueryable<> it is not the case. Also join is less flexible.

the_joric
  • 11,986
  • 6
  • 36
  • 57
13

Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:

from dealer in db.Dealers
from contact in dealer.DealerContacts
select new { whatever you need from dealer or contact }

It translates to a where clause:

SELECT <columns>
FROM Dealer, DealerContact
WHERE Dealer.DealerID = DealerContact.DealerID
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
5

Inner join two tables in linq C#

var result = from q1 in table1
             join q2 in table2
             on q1.Customer_Id equals q2.Customer_Id
             select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
wazz
  • 4,953
  • 5
  • 20
  • 34
Md Shahriar
  • 2,072
  • 22
  • 11
3

Use LINQ joins to perform Inner Join.

var employeeInfo = from emp in db.Employees
                   join dept in db.Departments
                   on emp.Eid equals dept.Eid 
                   select new
                   {
                    emp.Ename,
                    dept.Dname,
                    emp.Elocation
                   };
vzwick
  • 11,008
  • 5
  • 43
  • 63
Uthaiah
  • 1,283
  • 13
  • 14
3

Try this :

     var data =(from t1 in dataContext.Table1 join 
                 t2 in dataContext.Table2 on 
                 t1.field equals t2.field 
                 orderby t1.Id select t1).ToList(); 
Ajay
  • 6,418
  • 18
  • 79
  • 130
2
OperationDataContext odDataContext = new OperationDataContext();    
        var studentInfo = from student in odDataContext.STUDENTs
                          join course in odDataContext.COURSEs
                          on student.course_id equals course.course_id
                          select new { student.student_name, student.student_city, course.course_name, course.course_desc };

Where student and course tables have primary key and foreign key relationship

Sandeep Shekhawat
  • 685
  • 1
  • 9
  • 19
2

try instead this,

var dealer = from d in Dealer
             join dc in DealerContact on d.DealerID equals dc.DealerID
             select d;
Milan
  • 3,005
  • 1
  • 24
  • 26
1
var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName

}).ToList();
Ankita_Shrivastava
  • 1,225
  • 11
  • 9
1
var data=(from t in db.your tableName(t1) 
          join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
          (where condtion)).tolist();
sanket parikh
  • 281
  • 2
  • 8
1
var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
   select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();

Write table names you want, and initialize the select to get the result of fields.

Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
  • var list = (from u in db.Yourfirsttablename join c in db.secondtablename on u.firsttablecommonfields equals c.secondtablecommon field where u.Username == username select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First(); – Sarfraj Sutar Dec 23 '17 at 07:50
1

from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}

Rutu
  • 11
  • 1
-6

One Best example

Table Names : TBL_Emp and TBL_Dep

var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
 emp.Name;
 emp.Address
 dep.Department_Name
}


foreach(char item in result)
 { // to do}
JDB
  • 25,172
  • 5
  • 72
  • 123
Prasad KM
  • 31
  • 1