Home > Software engineering >  How do I limit the number of rows displayed
How do I limit the number of rows displayed

Time:11-17

I construct the below query to display data from Json. Assume this query returns 50 rows. But I want only first 10 rows to be displayed.
What is the equivalent of select top 10 or limit 10 in this scenario. Thank you.

List<Item> result = items.GroupBy(x => x.ItemNo)
       .Select(x => new Item
        {
            ItemNo = x.Key,
            ItemName = x.FirstOrDefault(y => y.Key == "ItemName")?.Value,           
            Date = x.FirstOrDefault(y => y.Key == "Date")?.Value
        }).OrderByDescending(y => y.date)
.ToList();

CodePudding user response:

In any query into your data pipeline you should NEVER request the lot. Why? You have no idea how many records there are in a query. You may think there are only a few but if a DBAdmin has done something wrong, there may be 10 million rows in the customer table.

So use a Request query object to request your data with some boundary condition values set by default.

public record ListQueryRequest {

    public int StartIndex { get; init; } = 0;

    public int PageSize { get; init; } = 1000;
}

Your data pipeline service can then do something like this:

private async ValueTask<ListRequestResult<TRecord>> GetItemsAsync<TRecord>(ListQueryRequest listQuery)
{

   using var dbContext = this.factory.CreateDbContext();
   dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

   IQueryable<TRecord> query = dbContext.Set<TRecord>();

   /.... any IQueryable conditions such as filtering or ordering

   query = query
     .Skip(listQuery.StartIndex)
     .Take(listQuery.PageSize);
   

  // delayed execution of the query
   var list = await query.ToListAsync(); 
  
   // build and return your request result
}

Where the result object template looks like this:


public record ListQueryResult<TRecord>
{
   public bool Successful {get; init;}
   public string Message {get; init;}
   public IEnumerable<TRecord> Items {get; init;}
}

CodePudding user response:

I think that the method you are looking for is Take

Take method from Microsoft website

In the end I think your code should look like this:

List<Item> result = items.GroupBy(x => x.ItemNo)
   .Select(x => new Item
    {
        ItemNo = x.Key,
        ItemName = x.FirstOrDefault(y => y.Key == "ItemName")?.Value,           
        Date = x.FirstOrDefault(y => y.Key == "Date")?.Value
    }).OrderByDescending(y => y.date).Take(10).ToList();
  • Related