Summary#
.Distinct() removes duplicates from a result. It takes no arguments — "distinct" means the whole row, exactly as
in SQL.
Signature#
<query>.Distinct().ToList()Description#
On whole rows it does nothing#
Entity rows are already unique — each has its own Id — so Order.Where(…).Distinct() cannot remove anything. It is
harmless, and it is also pointless, and writing it usually means someone expected it to do something it does not:
entity Order {
[Required] string Code;
[MaxLength(100)] string Region;
decimal Total;
}
Order[] All() {
return Order.Where(o => o.Total > 0).Distinct().ToList(); // same rows, either way
}If what you meant was "one order per region", that is not Distinct — it is a grouping, or a projection of the region
alone.
When does Distinct actually remove something?#
Duplicates are real the moment you stop selecting whole rows. Two orders from the same region project to the same
region string — and that is where Distinct does the work you wanted:
int RegionCount() {
return Order.Where(o => o.Total > 0).Distinct().ToList().Count;
}What does Distinct cost?#
De-duplicating means the database must compare rows, which usually means sorting them. On a large result that is real
work. If you are reaching for Distinct to paper over a join that is producing duplicates, fix the join — the
duplicates are a symptom, and Distinct only hides it.
See also#
- Where / Single / Count — the query being de-duplicated
- ToList — materialising the result
- Union / Concat / Intersect / Except — union / intersect / except, which also concern duplicates