简体   繁体   English

Linq查询-联接2个表

[英]Linq query - Join 2 tables

I want to make a join between 2 tables as you can see in the picture. 如图所示,我想在2个表之间建立连接。

在SITE和CONFIGURE之间联接

I just start on C#. 我只是从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 : 这里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. SITE和CONFIGURE是数据库或存储中的不同表。 You should then have references to both those tables and your query will look like this (assuming the CONFIGURE-table is referenced as lconfigure): 然后,您应该对这两个表都有引用,查询将如下所示(假设CONFIGURE表被引用为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. 但是,如果声明示例仅显示一个站点列表,然后查看您的查询似乎试图执行的操作,则实际上是在找到所有引用了具有相同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. 如果要这样做,可以先将所有CONFIGURECollection:s添加到一个列表中并使用它。

     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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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