【问题标题】:using multiple IEnumerable Joins使用多个 IEnumerable 连接
【发布时间】: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


【解决方案1】:

我同意@juharr 的评论。 LINQ 查询格式有时比流畅的 API 样式更清楚意图。以下是查询的编写方式。

var rows = from GpRow in _context.GpRows
    join ShopInfo in _context.ShopInfos on GpRow.ShopId equals ShopInfo.ShopId
    orderby GpRow.ShopId descending, GpRow.Month descending, ShopInfo.State, ShopInfo.ShopName
    select 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
    };

【讨论】:

    猜你喜欢
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多