连接两个序列

使用 Concat 运算符可串联两个序列。

Concat 运算符是为有序多重集定义的,其中接收方的顺序与参数的顺序相同。

在 SQL 中排序是产生结果前的最后一步。 因此,Concat 运算符是通过使用 UNION ALL 实现的,并且不保留其自变量的顺序。 为确保结果中的顺序正确,一定要显式地对结果进行排序。

示例 1

此示例使用 Concat 返回由所有 CustomerEmployee 的电话和传真号码组成的序列。

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);
}

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

示例 2

此示例使用 Concat 返回由所有 CustomerEmployee 的名字和电话号码映射组成的序列。

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);
}
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

请参阅