【问题标题】:How to write this code using the Linq Extension Method-Syntax?如何使用 Linq 扩展方法-语法编写此代码?
【发布时间】:2019-12-09 18:55:40
【问题描述】:

我有以下来自 Linq 示例的类:

public class Customer
{
    public Customer();

    public Cities City { get; set; }
    public string Name { get; set; }
    public Order[] Orders { get; set; }
}

public class Product
{
    public Product();

    public double Price { get; set; }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

public class Order
{
    public Order();

    public int OrderID { get; set; }
    public int ProductID { get; set; }
    public int Quantity { get; set; }
    public bool Shipped { get; set; }
}

static void Main(string[] args)
{
    var allOrders = from cust in customers
                    from ord in cust.Orders
                    join prod in products on ord.ProductID equals prod.ProductID
                    select new
                    {
                        cust.Name,
                        ord.ProductID,
                        OrderAmount = ord.Quantity * prod.Price
                    };
}

我想用 linq Extension Method Syntax 创建相同的集合(NameProductIDOrderamount)。我的问题是我不知道如何实现Extension Method Syntax中的两个数据源from cust in customers from ord in cust.Orders。 有谁知道它是如何工作的?

我知道了,但我无法访问集合中的 `CustomerName。

var allOrders2 =
    customers.SelectMany(cust => cust.Orders)
             .Join(products,
                   ord => ord.ProductID,
                   prod => prod.ProductID,
                   (ord, prod) => new
                   {
                       ord.ProductID,
                       OrderAmount = ord.Quantity * prod.Price
                   });

【问题讨论】:

  • 有什么特别的原因为什么要转向方法语法而不只是坚持查询语法?
  • Multiple field selection 可能会对您有所帮助。
  • 为此创建扩展方法绝对是矫枉过正。扩展方法应该是非常通用的类型和任务。如果这是出于减少代码复制的动机,那么您就是在隐藏 IMO 而不是修复架构缺陷。
  • 在使用查询或扩展方法时是否有一般规则?

标签: c# linq


【解决方案1】:

如果您的订单不涉及客户,诀窍是首先创建一个数据集,将客户和订单联系在一起:

customers
   .SelectMany(c => c.Orders.Select(o => new {
       cust = c,
       ord = o
   }))

然后在这个CustomerOrder (co) 上你可以申请加入:

...
    .Join(products, 
        co => co.ord.ProductID, 
        prod => prod.ProductID, 
        (co,prod) => new {
          co.cust.Name,
          co.ord.ProductID, 
          OrderAmount = ord.Quantity * prod.Price});

【讨论】:

    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 2011-11-08
    • 2018-02-23
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2021-11-05
    • 2011-11-19
    相关资源
    最近更新 更多