如何使用lambda表达式连接3个表

本文关键字:连接 3个表 表达式 lambda 何使用 | 更新日期: 2023-09-27 18:22:31

我有一个简单的LINQ lambda联接查询,但我想添加一个带有where子句的第三个联接。我该怎么做?

这是我的单一加入查询:

var myList = Companies
    .Join(
        Sectors,
        comp => comp.Sector_code,
        sect => sect.Sector_code,
        (comp, sect) => new {Company = comp, Sector = sect} )
    .Select( c => new {
        c.Company.Equity_cusip,
        c.Company.Company_name,
        c.Company.Primary_exchange,
        c.Company.Sector_code,
        c.Sector.Description
    });

我想将以下SQL命令添加到上面的LINQ查询中,并且仍然维护投影:

SELECT
    sector_code, industry_code 
FROM
    distribution_sector_industry 
WHERE
    service = 'numerical'

第三次连接将与Sector表&sector_code上的Distribution_sector_industry。

提前谢谢。

如何使用lambda表达式连接3个表

只是猜测:

var myList = Companies
    .Join(
        Sectors, 
        comp => comp.Sector_code,
        sect => sect.Sector_code,
        (comp, sect) => new { Company = comp, Sector = sect })
    .Join(
        DistributionSectorIndustry.Where(dsi => dsi.Service == "numerical"), 
        cs => cs.Sector.Sector_code,
        dsi => dsi.Sector_code,
        (cs, dsi) => new { cs.Company, cs.Sector, IndustryCode = dsi.Industry_code })
    .Select(c => new {
        c.Company.Equity_cusip,
        c.Company.Company_name,
        c.Company.Primary_exchange,
        c.Company.Sector_code,
        c.Sector.Description,
        c.IndustryCode
});

好吧,我不明白为什么你已经知道要选择sector_code,但我认为你想要这个:

var query = from company in Companies
            join sector in Sectors
              on company.SectorCode equals sector.SectorCode
            join industry in DistributionSectorIndustry
              on sector.SectorCode equals industry.SectorCode
            where industry.Service == "numerical"
            select new {
                company.EquityCusip,
                company.CompanyName,
                company.PrimaryExchange,
                company.SectorCode,
                sector.Description,
                industry.IndustryCode
            };

注:

  • 我把它改成了一个查询表达式,因为这是一种更可读的方式来表达这样的查询
  • 尽管"where"子句位于联接之后,但假设这是一个LINQ to SQL或Entity Framework查询,应该不会有任何区别
  • 为了清晰起见,我延长了变量名称的范围
  • 我已经将您的其他名称转换为传统的.NET名称;你也可以在你的模型中这样做

对于4个表

var query = CurrencyDeposits
.Join(Customers, cd => cd.CustomerId, cus => cus.Id, (cd, cus) 
=> new { CurrencyDeposit = cd, Customer = cus })
.Join(Currencies, x => x.CurrencyDeposit.CurrencyId, cr => cr.Id, (x, cr) 
=> new { x.CurrencyDeposit, x.Customer, Currency =  cr })
.Join(Banks, x => x.CurrencyDeposit.BankId, bn => bn.Id, (x, bn) 
=> new { x.CurrencyDeposit, x.Customer, x.Currency, Bank = bn})
.Select(s => new {
s.CurrencyDeposit.Id,
s.Customer.NameSurname,
s.Currency.Code,
s.Bank.BankName,
s.CurrencyDeposit.RequesCode
});

试试这样的。。。

var myList = ({from a in Companies 
join b in Sectors on a.Sector_code equals b.Sector_code
join c in Distribution on b.distribution_code equals a.distribution_code
select new {...});