【发布时间】: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 创建相同的集合(Name、ProductID、Orderamount)。我的问题是我不知道如何实现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 而不是修复架构缺陷。
-
在使用查询或扩展方法时是否有一般规则?