HOW TO:串連兩個序列 (LINQ to SQL)
使用 Concat<TSource> 運算子可串連兩個序列。
Concat<TSource> 運算子是針對已排序的多重集 (Multiset) 所定義,其中接收者和引數的順序相同。
產生結果前的最後一個步驟就是在 SQL 中進行排序。 基於這個理由,會使用 UNION ALL 實作 Concat<TSource> 運算子,但不保留其引數的順序。 若要確保結果的排序正確無誤,請務必明確地將結果排序。
範例
這個範例會使用 Concat<TSource> 傳回所有 Customer 和 Employee 電話及傳真號碼的序列。
Dim custQuery = _
(From c In db.Customers _
Select c.Phone) _
.Concat _
(From c In db.Customers _
Select c.Fax) _
.Concat _
(From e In db.Employees _
Select e.HomePhone)
For Each custData In custQuery
Console.WriteLine(custData)
Next
IQueryable<String> custQuery =
(from cust in db.Customers
select cust.Phone)
.Concat
(from cust in db.Customers
select cust.Fax)
.Concat
(from emp in db.Employees
select emp.HomePhone)
;
foreach (var custData in custQuery)
{
Console.WriteLine(custData);
}
這個範例會使用 Concat<TSource> 傳回所有 Customer 和 Employee 姓名及電話號碼對應的序列。
Dim infoQuery = _
(From cust In db.Customers _
Select Name = cust.CompanyName, Phone = cust.Phone) _
.Concat _
(From emp In db.Employees _
Select Name = emp.FirstName & " " & emp.LastName, _
Phone = emp.HomePhone)
For Each infoData In infoQuery
Console.WriteLine("Name = " & infoData.Name & _
", Phone = " & infoData.Phone)
Next
var infoQuery =
(from cust in db.Customers
select new { Name = cust.CompanyName, cust.Phone }
)
.Concat
(from emp in db.Employees
select new
{
Name = emp.FirstName + " " + emp.LastName,
Phone = emp.HomePhone
}
);
foreach (var infoData in infoQuery)
{
Console.WriteLine("Name = {0}, Phone = {1}",
infoData.Name, infoData.Phone);
}