efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Translate LINQ DistinctBy

Open roji opened this issue 3 years ago • 5 comments

.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 (https://github.com/npgsql/efcore.pg/issues/894).

roji avatar Feb 18 '22 10:02 roji

I cannot wait for this feature to work!! 👍

Jacko1394 avatar Jun 09 '22 04:06 Jacko1394

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()

benmccallum avatar Jul 15 '22 05:07 benmccallum

@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.

roji avatar Jul 15 '22 11:07 roji

Is this feature dependent on first handling all these issues?

lonix1 avatar Jun 29 '24 03:06 lonix1

@lonix1 no; the above translation with GroupBy works at least in the basic case; there may be bugs in other, non-basic cases, but those don't prevent the basic transformation.

roji avatar Jun 29 '24 06:06 roji

Hi guys, are there any news on this? Thanks in advance for the feedback.

alainkaiser avatar Oct 28 '24 19:10 alainkaiser

No news at the moment.

roji avatar Oct 28 '24 21:10 roji