简体   繁体   English

Linq 查询不使用连接两个表不同的值

[英]Linq query without using Joins for two tables distinct value

Table 1表格1

Contract ID , Vendor Name, Description , user合同 ID、供应商名称、描述、用户

Table 2表 2

Contract ID , product , department合同编号、产品、部门

Match condition : for all the Contract ID matching with table 1 , get their Vendor Name and Contract ID匹配条件:对于与表1匹配的所有合约ID,获取它们的供应商名称和合约ID

Query result output : Contract ID(Distinct),Vendor Name查询结果输出:Contract ID(Distinct),Vendor Name

Below code using inner join , need same output without using join as linq query \\\\下面使用内部连接的代码,需要相同的输出而不使用连接作为 linq 查询 \\\\

   select table1.Contract ID,table1.Vendor Name ,table2.Contract ID
   from table1 as s1
   inner join table2 as s2
   on s1.Contract ID=s2.Contract ID

\\\

Thanks in Advance提前致谢

Considering you need only Join alternative to select distinct ,you can use inner query logic like below to write LINQ SELECT contractorid ,vendor name Where Contracterid in (Select distinct contractor id from table2)考虑到您只需要 Join 替代选择不同的,您可以使用如下的内部查询逻辑来编写 LINQ SELECT 承包商 ID,供应商名称 Where Contracterid in (Select distinct contract id from table2)

Here assumption is contractorId is primary key in table 1这里假设contractorId是表1中的主键

If I understand correctly, you want to retrieve a collection of objects containing Contract Id and Vendor Names, without duplicates, whose Contract Id is found in Table 2.如果我理解正确,您想要检索包含合同 ID 和供应商名称的对象集合,没有重复,其合同 ID 见表 2。

It is unclear if you are using Linq to objects, Linq to Entities, or any other Linq flavor, which would have a meaningful impact on how to best construct a query for a specific purpose.不清楚您是使用 Linq to objects、Linq to Entities 还是任何其他 Linq 风格,这将对如何最好地构造特定目的的查询产生有意义的影响。

But as a first hint, here is a way to perform this without join with Linq:但作为第一个提示,这里有一种无需加入 Linq 即可执行此操作的方法:

// Get a list of all distinct Contract Ids in Table 2
var AllTable2ContractIds = Table2
    .Select(e => e.ContractId)
    .Distinct()
    .ToList();

// With Table 1
// Keep only entries whose contract Id is found in the list just contructed above.
// transform it to keep Contract Id and Vendor Name.
// The use of ToList() at the end is not mandatory.
// It depends if you want to materialize the result or not.
var Result = Table1
    .Where(e => AllTable2ContractIds.Contains(e.ContractId))
    .Select(e => new 
    {
        e.ContractId,
        e.VendorName
    })
    .ToList();

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

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