简体   繁体   中英

Linq query - Join 2 tables

I want to make a join between 2 tables as you can see in the picture.

在SITE和CONFIGURE之间联接

I just start on C#.

Here what I've already done :

var sitesDB = from sites in this.lSites
    from configure in sites.CONFIGURECollection
    where sites.ID == configure.SITE_ID
    select sites.KEY;

It's not working.

And :

var sitesDB = from sites in this.lSites
    from configure in sites.CONFIGURECollection
    join config in this.lSites on sites.ID equals config.ID
    select sites.KEY;

Not working.

Here the declaration of lSites :

public List<SITE> lSites { get; private set; }

I want to make this join because I have to add columns in a table according to this join. Thank you ! :)

I have three possible solutions to you based on the possibilities of what you might be trying to do:

  1. SITE and CONFIGURE are different tables in a database or storage. You should then have references to both those tables and your query will look like this (assuming the CONFIGURE-table is referenced as lconfigure):

     var sitesDB = from site in lsites join config in lconfigure on sites.ID equals config.ID select site.Key; 
  2. However if you only have the one list of sites as your declaration example shows then looking at what your query seems to attempt to do, you are actually after finding all sites that have references to configurations with the same ID. This query will do that:

     var sitesDB = from site in lsites where site.CONFIGURECollection.Where(x => x.ID == l1.ID).FirstOrDefault() != null select site.Key; 
  3. The fundamental problem is that you are trying to join the tables on each site with all sites. If you want to do that you can first add all CONFIGURECollection:s into one list and use that.

     var lconfigure = new List<CONFIGURE>(); foreach (var site in sites) { lconfigure.AddRange(site.CONFIGURECollection); } 

After that you use the first query I listed.

Do you want something like this:

from sites in this.lSites
join configure in sites.CONFIGURECollection on sites.ID equals configure.SITE_ID
select sites.key;

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