How to: Concatenate Two Sequences (LINQ to SQL)
Use the Concat<TSource> operator to concatenate two sequences.
The Concat<TSource> operator is defined for ordered multisets where the orders of the receiver and the argument are the same.
Ordering in SQL is the final step before results are produced. For this reason, the Concat<TSource> operator is implemented by using UNION ALL and does not preserve the order of its arguments. To make sure ordering is correct in the results, make sure to explicitly order the results.
Example
This example uses Concat<TSource> to return a sequence of all Customer and Employee telephone and fax numbers.
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);
}
This example uses Concat<TSource> to return a sequence of all Customer and Employee name and telephone number mappings.
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);
}
See Also
Reference
Standard Query Operator Translation (LINQ to SQL)