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

时间:2012-02-02 21:14:46

标签: c# linq join lambda

我有一个简单的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'

第3次加入将使用Sector table& sector_sector_industry on sector_code。

提前致谢。

4 个答案:

答案 0 :(得分:30)

只是一个猜测:

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
});

答案 1 :(得分:14)

好的,我不明白你为什么要在你已经知道的时候选择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名称;您也可以在模型中执行此操作

答案 2 :(得分:2)

尝试这样的事情......

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 {...});

答案 3 :(得分:1)

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
});