我正在通过101个linq示例编写代码,现在我正处于#106。
我正在尝试用方法/ lambda语法重写查询表达式以供我自己学习。
以下是示例代码:
List<Customer> customers = GetCustomerList();
List<Supplier> suppliers = GetSupplierList();
var custSuppliers =
from cust in customers
join sup in suppliers on cust.Country equals sup.Country into ss
from s in ss.DefaultIfEmpty()
orderby cust.CompanyName
select new
{
Country = cust.Country,
CompanyName = cust.CompanyName,
SupplierName = s == null ? "(No suppliers)" : s.SupplierName
};
这是我到目前为止所做的:
var custSuppliers =
customers.GroupJoin(suppliers, c => c.Country, s => s.Country, (c, s) => new { Customers = customers, Suppliers = suppliers })
.OrderBy(i => i.Customers)
.SelectMany(x => x.Suppliers.DefaultIfEmpty(), (x, p) => // p is the many field (i.e. customers)
new
{
CompanyName = x.CompanyName, // no definition for CompanyName
Country = p.Country,
SupplierName = p.SupplierName == null ? "(No suppliers)" : p.SupplierName
});
我的理解是SelectMany接受参数X和P,其中X是“左”表(即最多有1个),P是“右”表,其中可能有N个(或者为null) )。
但是,不是持有单个客户的X变量,而是拥有供应商和客户的集合。
有谁能解释这里发生了什么?