【发布时间】:2020-08-26 03:36:50
【问题描述】:
如果我有 3 张桌子。如何使用 IEnumerable LINQ Joins 将所有 3 个表连接在一起?这是我当前的查询,我想使用 GPRow id = Budgettargets id 加入另一个名为 BudgetTargets 的 IEnumerable
var rows = _context.GpRows.Join(
_context.ShopInfos,
GpRow => GpRow.ShopId,
ShopInfo => ShopInfo.ShopId,
(GpRow, ShopInfo) => new{
ShopName = ShopInfo.ShopName,
State = ShopInfo.State,
YearMonth = String.Concat(GpRow.Year, GpRow.Month),
GpRow.Year,
GpRow.Month,
GpRow.Id,
GpRow.ShopId,
GpRow.PaintSale,
GpRow.PanelSale,
GpRow.PartsSale,
GpRow.OtherSale,
GpRow.PaintCost,
GpRow.PanelCost,
GpRow.PartsCost,
GpRow.OtherCost,
GpRow.PanelWages,
GpRow.PaintWages,
GpRow.Depreciation,
GpRow.ForecastedSales,
GpRow.Expenses
}
)
.Where(GpRow => shopId_Array.Contains(GpRow.ShopId))
.OrderByDescending(a => a.Year).OrderByDescending(b => b.Month).ThenBy(c => c.State).ThenBy(c => c.ShopName)
.ToList();
【问题讨论】:
-
如果这是 EF,我建议考虑使用 Navigation 属性,假设您要加入的表具有正确的 FK 设置。或者您可能会发现这更容易用查询语法编写,例如
from x in table1 join y in table2 on x.Id equals y.XId join z in table3 on y.Id equals z.YId -
谢谢 Juharr 但是加入只返回匹配我想要一个左加入:(
-
@MichaelZerofiveJenkins,请检查this 是否有帮助。如果是left join,你可能需要考虑
DefaultIfEmpty。 -
@MichaelZerofiveJenkins 您应该在问题中包含您想要左连接的内容。这些都是这样完成的
from x in table1 join y in table2 on x.Id equals y.XId into grp from y in grp.DefaultIfEmpty() -
如何将您的 cmets 标记为回答 Juharr?
标签: c# linq ienumerable