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 to create a new Telerik Data Access Domain Model based on the Northwind database.

The following code is the LINQ example.

C#


    using ( EntitiesModel dbContext = new EntitiesModel() )
    {
       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 );
    }

VB.NET


    Using dbContext As New EntitiesModel()
     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