-1

I want to return 20 items foreach grouping without loading to memory (I shouldn't use AsEnumerable). I couldn't find the way how:

_context.Products
        .Where(predicate)
        .Select(t => new ProductViewModel
           {
              foo = bar
           }).OrderBy(t => Guid.NewGuid()).AsNoTracking()
        .GroupBy(t => new { CategoryName = t.CategoryName, Id = t.CategoryId })
        .Take(20); //??
seme
  • 51
  • 5
  • 2
    Which ORM do you use and which version? Put right tags. – Svyatoslav Danyliv Jun 20 '22 at 07:54
  • 2
    Does this answer your question? [How to select top N rows for each group in a Entity Framework GroupBy with EF 3.1](https://stackoverflow.com/questions/59456026/how-to-select-top-n-rows-for-each-group-in-a-entity-framework-groupby-with-ef-3) – Peter Csala Jun 20 '22 at 08:19
  • 1
    @PeterCsala Yes. Updated to EF Core 6.0 and it's working. Thanks – seme Jun 20 '22 at 12:23

1 Answers1

0
_context.Products
        .Where(predicate)
        .Select(t => new ProductViewModel
           {
              foo = bar
           })
        // .OrderBy(t => Guid.NewGuid()) Sorting by a Guid is a shuffle
        .AsNoTracking()
        .GroupBy(t => new { CategoryName = t.CategoryName, Id = t.CategoryId })
        .Select(xs => xs.Take(20));
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 3
    I would find it helpful to know why this answers the question - what difference does the `select` make. Thanks. – Peter Smith Jun 20 '22 at 07:47
  • That returns `IQueryable>`. Where can I find the `Key` of the grouping – seme Jun 20 '22 at 07:49
  • 1
    The key is on the grouping as `.Key`, see: https://learn.microsoft.com/en-us/dotnet/api/system.linq.igrouping-2?view=net-6.0 – sdgfsdh Jun 20 '22 at 08:37