如何将以下 LINQ 查询语法转换为具有 Lambda 表达式的扩展语法?我正在尝试从第 11.3.9 章的伽利略计算开放书 C#2012 中学习。 以下是使用的类:
public class Customer
{ public string Name { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{ public int OrderID { get; set; }
public int ProductID { get; set; }
public int Quantity { get; set; }
}
public class Product
{ public int ProductID { get; set; }
public double Price { get; set; }
}
在 customerList 中有一些“Customer”对象,在 Orders 属性中您可以找到“Order”对象的列表。 这是我想用 lambda 表达式编写的代码:
var allOrders =
from cust in customerList
from ord in cust.Orders
join prod in productList on ord.ProductID equals prod.ProductID
select new
{
cust.Name,
ord.ProductID,
OrderAmount = ord.Quantity * prod.Price
};
var summe =
from cust in customerList
join ord in allOrders
on cust.Name equals ord.Name into custWithOrd
select new { cust.Name, TotalSumme = custWithOrd.Sum(s => s.OrderAmount) };
我想我应该使用 GroupJoin 但我不知道如何在没有任何“from”的情况下编写它 如果你能给我看看就好了。
最佳答案
翻译的两个查询:
var allOrders2 = customerList.SelectMany(cust => cust.Orders,
(cust, ord) => new
{
cust,
ord
})
.Join(productList,
x => x.ord.ProductID,
prod => prod.ProductID,
(x, prod) => new
{
Name = x.cust.Name,
ProductID = x.ord.ProductID,
OrderAmount = (double)x.ord.Quantity * prod.Price
});
var summe2 = customerList.GroupJoin(allOrders,
cust => cust.Name,
ord => ord.Name,
(cust, custWithOrd) => new
{
Name = cust.Name,
TotalSumme = custWithOrd.Sum(s => s.OrderAmount)
});
关于C# LINQ 转换查询语法扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21133246/