When working with collections in C#, one of the common requirements is removing duplicate records. LINQ provides several ways to handle duplicates, including Distinct(), DistinctBy() and GroupBy().
Although all three can be used to work with duplicate data, they serve different purposes.
Distinct()removes duplicate elements based on equality of the elements themselves.DistinctBy()removes duplicates based on a selected property or key.GroupBy()groups elements based on a key and allows you to work with each group.
In this article, we'll explore the differences between these three LINQ methods using practical C# examples and understand when to use each.
1. Understanding the sample data
Let's use a simple Employee class for our examples.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}We'll create a sample collection containing duplicate employee records.
var employees = new List<Employee>
{
new Employee { Id = 1, Name = "John", Department = "IT" },
new Employee { Id = 2, Name = "Mary", Department = "HR" },
new Employee { Id = 3, Name = "John", Department = "IT" },
new Employee { Id = 4, Name = "David", Department = "IT" },
new Employee { Id = 5, Name = "Mary", Department = "HR" },
new Employee { Id = 6, Name = "Peter", Department = "Finance" }
};Notice that John and Mary appear more than once. However, these are different Employee objects with different IDs.
Let's see how each LINQ method handles this data.
2. Using Distinct() in C#
The Distinct() method returns unique elements from a collection using the equality comparer for the element type.
Example 1: Distinct with strings
var names = new List<string>
{
"John",
"Mary",
"John",
"David",
"Mary",
"Peter"
};
var uniqueNames = names.Distinct();
foreach (var name in uniqueNames)
{
Console.WriteLine(name);
}Output:
John
Mary
David
PeterSince strings have value-based equality, Distinct() can identify duplicate string values.
Example 2: Distinct with custom objects
Now let's try using Distinct() with our Employee collection.
var uniqueEmployees = employees.Distinct();
foreach (var employee in uniqueEmployees)
{
Console.WriteLine($"{employee.Id} - {employee.Name} - {employee.Department}");
}Will this remove duplicate employees based on their Name or Department?
Not automatically.
For a typical class that doesn't override equality or implement a custom equality comparer, two separate Employee objects are considered different even if their properties have identical values.
Therefore, the above code will return all six employee objects.
Distinct() doesn't automatically compare every property of a custom object.
If you want to compare custom objects based on their properties, you can implement equality using IEquatable<T> or supply an IEqualityComparer<T>.
However, for removing duplicates based on a specific property, DistinctBy() is often simpler.
3. Using DistinctBy() in C#
DistinctBy() was introduced in .NET 6 and provides a simpler way to remove duplicates based on a selected key.
Instead of comparing entire objects, you specify which property should be used to determine uniqueness.
Example: Remove duplicate employees based on Name
var uniqueEmployees = employees.DistinctBy(e => e.Name);
foreach (var employee in uniqueEmployees)
{
Console.WriteLine($"{employee.Id} - {employee.Name} - {employee.Department}");
}Output:
1 - John - IT
2 - Mary - HR
4 - David - IT
6 - Peter - FinanceIn this example, DistinctBy(e => e.Name) uses the Name property as the key.
Only one employee for each unique name is returned.
Remove duplicates based on multiple properties
What if we want to remove duplicates based on both Name and Department?
We can use an anonymous object as the key.
var uniqueEmployees = employees.DistinctBy(
e => new { e.Name, e.Department });This considers the combination of Name and Department when determining uniqueness.
For example, two employees with the same name but different departments will be treated as distinct.
When should you use DistinctBy()?
Use DistinctBy() when:
You want to remove duplicate records based on a particular property.
You want to retain an element from each unique key.
You don't need the entire group of duplicate records.
You want a concise alternative to grouping and selecting a representative record.
It's particularly useful when working with collections of objects returned from APIs, services or in-memory data processing.
4. Using GroupBy() in C#
Unlike Distinct() and DistinctBy(), GroupBy() doesn't simply remove duplicate elements.
It groups elements based on a specified key and returns a collection of groups.
Each group contains the key and all elements associated with that key.
Example: Group employees by Department
var employeeGroups = employees.GroupBy(e => e.Department);
foreach (var group in employeeGroups)
{
Console.WriteLine($"Department: {group.Key}");
foreach (var employee in group)
{
Console.WriteLine($" {employee.Name}");
}
}Output:
Department: IT
John
John
David
Department: HR
Mary
Mary
Department: Finance
PeterHere, GroupBy() creates three groups:
IT
HR
Finance
Unlike DistinctBy(), it retains all the elements within each group.
Example: Group and select one employee per Name
You can also use GroupBy() to remove duplicates by selecting one element from each group.
var uniqueEmployees = employees
.GroupBy(e => e.Name)
.Select(g => g.First());This produces one employee for each unique name.
This is similar in purpose to:
var uniqueEmployees = employees.DistinctBy(e => e.Name);However, GroupBy() is more useful when you need access to the entire group or when additional processing is required for each group.
Example: Group employees and calculate the count
var employeeCountByDepartment = employees
.GroupBy(e => e.Department)
.Select(g => new
{
Department = g.Key,
Count = g.Count()
});Output:
IT - 3
HR - 2
Finance - 1This is where GroupBy() becomes more useful than simply removing duplicates.
5. Distinct vs DistinctBy vs GroupBy
| Method | Purpose | Example |
|---|---|---|
Distinct() | Removes duplicate elements based on equality | numbers.Distinct() |
DistinctBy() | Removes duplicates based on a selected key | employees.DistinctBy(e => e.Name) |
GroupBy() | Groups elements based on a key | employees.GroupBy(e => e.Department) |
Which one should you use?
Use Distinct()
When you want unique values from a collection and the element equality is already defined appropriately.
var uniqueNumbers = numbers.Distinct();Use DistinctBy()
When you want one representative element for each unique property or key.
var uniqueEmployees = employees.DistinctBy(e => e.Name);Use GroupBy()
When you want to group records and perform additional operations such as counting, aggregation, filtering or selecting elements from each group.
var departments = employees.GroupBy(e => e.Department);6. Performance considerations
For in-memory LINQ operations (IEnumerable<T>), all three methods generally require processing the input collection.
Distinct()maintains a set of elements to identify duplicates.DistinctBy()maintains a set of keys to identify duplicates.GroupBy()builds groups and retains the elements belonging to those groups.
For typical in-memory scenarios, these operations generally have O(n) time complexity under normal hash-based assumptions, though actual performance depends on equality comparisons, hashing and data characteristics.
GroupBy() can require more memory because it retains the elements within the groups, whereas Distinct() and DistinctBy() primarily maintain the elements or keys needed to identify uniqueness.
For large collections, consider memory usage, the type of processing required, and whether the data can be filtered or processed at the source.
7. What about Entity Framework Core?
When working with Entity Framework Core, you're often dealing with IQueryable<T> instead of IEnumerable<T>.
This means LINQ expressions may be translated into SQL and executed by the database.
Not every LINQ method or expression is supported equally by every provider or version.
For example, a query using DistinctBy() may not translate to SQL in your particular EF Core version or provider. In such cases, you may need to use a different query pattern, such as GroupBy(), a projection, or a database-specific query.
Always check the generated SQL and test the query against your actual database provider.
Don't assume that an in-memory LINQ operation behaves identically when executed against a database.
Conclusion
Distinct(), DistinctBy() and GroupBy() are useful LINQ methods, but choosing the right one depends on what you're trying to achieve.
Use
Distinct()for unique elements.Use
DistinctBy()for unique elements based on a specific property.Use
GroupBy()when you need to group and process multiple elements together.
For most in-memory scenarios where you simply want to remove duplicate objects based on a property, DistinctBy() is often the cleanest option.
If you need to process the duplicate records themselves, GroupBy() is the better choice.
Understanding the difference will help you write cleaner, more readable and efficient LINQ code.