如何使用lambda表达式连接3个表?
我有一个简单的LINQ lambda连接查询,但我想添加一个带有where子句的第3个连接。 我该怎么做呢?
这是我的单个连接查询:
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_code上的Sector表和Distribution_sector_industry进行。
提前致谢。
只是一个猜测:
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名称; 您也可以在模型中执行此操作
试试这样的事……
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 {...});
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 });