How to Select Distinct Records with Entity Framework
When using Entity Framework (EF), you can easily retrieve distinct records from your database using LINQ. Here’s how to do it for both single and multiple columns:
- Distinct for a Single Column
To select distinct values from a single column, use theDistinct()method:
var distinctNames = DBContext.Addresses
.Select(m => m.NAME)
.Distinct()
.ToList();- Distinct for Multiple Columns
Let’s say you want to retrieve distinct combinations of both NAME and ID from the same Addresses table. Here’s how you can do it:
using (var context = new YourDbContext())
{
var distinctAddresses = context.Addresses
.Select(m => new { m.NAME, m.ID })
.Distinct()
.ToList();
}Explanation:
Select(m => new { m.NAME, m.ID }): This projects the query to select bothNAMEandIDcolumns as part of an object.Distinct(): This ensures that only unique combinations ofNAMEandIDare returned.ToList(): Converts the result into a list.
Performance ConsiderationsDistinct() can impact performance, especially with large datasets, as it requires sorting or comparing records to remove duplicates. Always test and optimize queries where necessary.
Get Hafiz Muhammad Asad’s stories in your inbox
Join Medium for free to get updates from this writer.
Conclusion
Using Distinct() in Entity Framework allows you to easily retrieve unique values based on one or more columns. Whether you're working with a single column or need to filter unique combinations of multiple columns, this simple method can help streamline your data queries and improve the efficiency of your application.
Let’s learn something new together!
Refrence
For details, check out my StackOverflow answer.







