0

我正在编写 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 个(或空值)。

但不是 X 变量包含单个客户,而是包含供应商和客户的集合。

谁能解释这里发生了什么?

4

0 回答 0