共用方式為


How to: Remove Duplicate Elements From LINQ to Entities Query Results

This topic provides examples of how to remove duplicate elements from query results by using Distinct. The examples in this topic are based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework). You can also use the Entity Data Model Wizard to define the AdventureWorks Sales Model. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework).

Example

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

Using AWEntities As New AdventureWorksEntities()
    Dim contacts = AWEntities.Contact

    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 AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Contact> contacts = AWEntities.Contact;
    IQueryable<string> contactsQuery = from c in contacts
                        select c.LastName;

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

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

Compiling the Code

The examples in this topic contain references to objects and namespaces that are defined in the sample project in How to: Create a LINQ to Entities Project in Visual Studio. To compile and run one of these examples, paste it into the Main method.

See Also

Other Resources

Querying an Entity Data Model (Entity Framework Tasks)