This documentation is archived and is not being maintained.

ObjectQuery<T>.Distinct Method

Limits the query to unique results.

Namespace:  System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

public ObjectQuery<T> Distinct()

Return Value

Type: System.Data.Objects.ObjectQuery<T>
A new ObjectQuery<T> instance that is equivalent to the original instance with SELECT DISTINCT applied.

This query builder method returns an ObjectQuery<T> instance that is equivalent to the original query with SELECT DISTINCT applied.

The DISTINCT operator cannot be applied to an object that includes a mapping to a non-comparable column in the data source (such as ntext).

The example in this topic is based on the Adventure Works Sales Model. The example uses UnionAll method to create a new ObjectQuery<T> object. Then it calls Distinct on the new ObjectQuery<T> object to get the unique results of this query.


int productID = 100;
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string queryString =
        @"SELECT VALUE product FROM AdventureWorksEntities.Products 
            AS product WHERE product.ProductID < @productID";

    ObjectQuery<Product> productQuery =
        new ObjectQuery<Product>(queryString,
            context, MergeOption.NoTracking);

    ObjectQuery<Product> productQuery2 =
        new ObjectQuery<Product>(queryString,
            context, MergeOption.NoTracking);

    ObjectQuery<Product> productQuery3 =
        productQuery.UnionAll(productQuery2);

    productQuery3.Parameters.Add(new ObjectParameter("productID", productID));

    Console.WriteLine("Result of UnionAll");
    Console.WriteLine("------------------");

    // Iterate through the collection of Product items, 
    // after the UnionAll method was called on two queries.
    foreach (Product result in productQuery3)
    {
        Console.WriteLine("Product Name: {0}", result.ProductID);
    }
    ObjectQuery<Product> productQuery4 = productQuery3.Distinct();

    Console.WriteLine("\nResult of Distinct");
    Console.WriteLine("------------------");

    // Iterate through the collection of Product items.
    // after the Distinct method was called on a query. 
    foreach (Product result in productQuery4)
        Console.WriteLine("Product Name: {0}", result.ProductID);
}


.NET Framework

Supported in: 4, 3.5 SP1

.NET Framework Client Profile

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Show: