Data Access has been discontinued. Please refer to this page for more information.

How to: Order Two Unionized Queries

This topic shows how to combine the results of two queries into a single result set, and then to order the result set.

To run the code in this example, you need a fluent model based on the Northwind database.

The following code is the LINQ example.

using ( FluentModel dbContext = new FluentModel() )
{
   var query = dbContext.Products.Select(
       ( product, index ) =>
           new
           {
               Name = product.ProductName,
               Pid = product.ProductID,
               Price = product.UnitPrice
           } ).
           Where( p => p.Name.StartsWith( "A" ) ).
           Union( dbContext.Products.Select(
               ( product, index ) => new
               {
                   Name = product.ProductName,
                   Pid = product.ProductID,
                   Price = product.UnitPrice
               } ).Where( p => p.Name.StartsWith( "B" ) ) ).OrderBy( p => p.Price );
   foreach ( var item in query )
       Console.WriteLine( item );
}
Using dbContext As New FluentModel()
    Dim query = dbContext.Products.Select(Function(product, index) New With {
        Key .Name = product.ProductName, 
        Key .Pid = product.ProductID, 
        Key .Price = product.UnitPrice
    }).Where(Function(p) p.Name.StartsWith("A"))
    .Union(dbContext.Products.Select(Function(product, index) New With {
        Key .Name = product.ProductName, 
        Key .Pid = product.ProductID, 
        Key .Price = product.UnitPrice}).Where(Function(p) p.Name.StartsWith("B")))
    .OrderBy(Function(p) p.Price)
    For Each item In query
        Console.WriteLine(item)
    Next item
End Using

See Also