私は 101 の linq の例をコーディングしており、現在は #106 です。
私自身の学習のために、メソッド/ラムダ構文でクエリ式を書き直そうとしています。
コード例は次のとおりです。
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 変数は単一の顧客を保持する代わりに、サプライヤーと顧客のコレクションを保持します。
ここで何が起こっているのか誰でも説明できますか?