How to: Remove Duplicate Elements From Query Results

This topic provides examples of how to remove duplicate elements from query results by using Distinct.

The example in this topic is based on the Adventure Works Sales Model. To run the code in this topic, you must have already added the Adventure Works Sales Model to your project and configured your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework) or How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

Description

This example uses the Distinct method to return unique last names.

Code

Using context As New AdventureWorksEntities()
    Dim contacts = context.Contacts

    Dim contactsQuery = _
        From c In contacts _
        Select c.LastName

    Dim distinctNames = contactsQuery.Distinct()

    For Each name In distinctNames
        Console.WriteLine("Name: " + name)
    Next
End Using
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<string> contactsQuery = from c in context.Contacts
                        select c.LastName;

    IQueryable<string> distinctNames = contactsQuery.Distinct();

    foreach (string name in distinctNames)
    {
        Console.WriteLine("Name: {0}", name);
    }
}

See Also

Concepts

Querying a Conceptual Model