dotnet / dotnet/efcore

Translate LINQ DistinctBy

Open
#27,470 9 comments 155 reactions 0 assignees View on GitHub
area-groupby area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

.NET 6.0 introduced [DistinctBy](https://docs.microsoft.com/en-us/dotnet/api/system.linq.queryable.distinctby), which we could translate.

DistinctBy can be rewritten as follows:

```c#
_ = blogs.DistinctBy(b => b.Id);

_ = blogs.GroupBy(b => b.Id).Select(g => g.First());
```

Note: since DistinctBy returns the first element with a given key, it is order-sensitive, and so we should issue a warning if it's used without OrderBy.

Note that PostgreSQL has a `DISTINCT ON` feature which is likely much more efficient than what we generate above (https://github.com/npgsql/efcore.pg/issues/894).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.