【问题标题】:join two or more list with Lambda but not using the method or type "Join"使用 Lambda 加入两个或多个列表,但不使用方法或键入“加入”
【发布时间】:2017-08-17 09:33:06
【问题描述】:

我对 C# 很陌生。我在映射器类中有一个方法,它接受两个参数 List1 和 List2 作为源并返回一个定义了字段的模型类列表。字段来自两种列表类型。

下面是类(SOHMapper)/方法(Map)

public class SOHMapper : ISOHMapper
{
    public List<StockonHand> Map(List<WarehouseOnHand> warehouseonhands, List<SPR_SKU> SKus)
    {
       var Stockonhands = warehouseonhands.Join(SKus, x1 => x1.ItemNumber, x2 => x2.ItemId, (x1, x2) => new
        { x1.Quantity, x1.ProductStyleId, x1.ItemNumber, x2.GNumber, x2.Style }).Join(SKus,
       x1 => x1.ProductStyleId, x2 => x2.Style, (x1, x2) => new
        { x1.Quantity, x1.ItemNumber, x2.GNumber }).GroupBy(g => new { g.GNumber, g.ItemNumber })
        .Select(n => new StockonHand
       {
           DFUCode = "\"" + n.Key.GNumber + "\"",
           ItemNumber = "\"" + n.Key.ItemNumber + "\"",
           CompanyCode = "\"" + "VPAC" + "\"",
           NoOfCases = n.Sum(s => s.Quantity),
           Date = DateTime.Now.ToString("dd/MM/yyyy")
       }).ToList();

       return Stockonhands;
    }
}

下面是我的模型类(Stockonhand):

public class StockonHand
{
    public string DFUCode { get; set; }
    public string ItemNumber { get; set; }
    public string CompanyCode { get; set; }
    public decimal NoOfCases { get; set; }
    public string Date { get; set; }
}

现在这工作正常,我得到了所需的数据。但要求是不要在 lambda 表达式中使用“Join”方法/关键字。有没有其他方法可以从 List 中提取列?有没有办法使用“Where”方法/关键字从两个不同的列表中获取字段?

【问题讨论】:

  • "但要求是不能在 lambda 表达式中使用 "Join" 方法/关键字。"这是一个奇怪的要求。 为什么你不能使用Join?每当您有奇怪的要求时,请详细说明要求的原因 - 否则可能会建议满足要求的解决方案,但会违反具有相同根本原因的一些其他未成文要求。
  • 谢谢大家的回复。这不是家庭作业,而是让我陷入困境的实际项目工作。我们的一位技术主管要求不要使用“加入”。我没有问他为什么。我会这样做并在这里发布。

标签: c# linq


【解决方案1】:

在方法语法中:

var result = warehouseonhands.SelectMany(w => SKus.Where(s => s.ItemId == w.ItemNumber)
                                                  .Select(s => new { w, s }));

在查询语法中:

var result = from w in warehouseonhands
             from s in SKus
             where w.ItemNumber == s.ItemId
             select new { w, s };

【讨论】:

  • @ArpanDG - 太棒了:)
猜你喜欢
  • 1970-01-01
  • 2014-02-23
  • 2018-10-15
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多