Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate LINQ DistinctBy #27470

Open
Tracked by #25570 ...
roji opened this issue Feb 18, 2022 · 3 comments
Open
Tracked by #25570 ...

Translate LINQ DistinctBy #27470

roji opened this issue Feb 18, 2022 · 3 comments

Comments

@roji
Copy link
Member

roji commented Feb 18, 2022

.NET 6.0 introduced DistinctBy, which we could translate.

DistinctBy can be rewritten as follows:

_ = 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 (npgsql/efcore.pg#894).

@Jacko1394
Copy link

I cannot wait for this feature to work!! 👍

@benmccallum
Copy link
Contributor

Would be cool to translate the following too, thought let me know if you want a separate issue.

_db.Posts
    .GroupBy(p => p.CategoryId)
    .Select(g => new
    {
        CategoryId = g.Key,
        NumberOfPosts = g.Count(),
        NumberOfTags = g.DistinctBy(p => p.TagId).Count()
   });

Though perhaps semantically this is a bit weird and the current way of doing it make more sense:

NumberOfTags = g.Select(p => p.TagId).Distinct().Count()

@roji
Copy link
Member Author

roji commented Jul 15, 2022

@benmccallum yeah, just projecting first makes more sense to me: DistinctBy really is for when you want the actual entities, rather than just counting them afterwards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants