简体   繁体   English

如何限制显示的行数

[英]How do I limit the number of rows displayed

I construct the below query to display data from Json. Assume this query returns 50 rows.我构造以下查询以显示来自 Json 的数据。假设此查询返回 50 行。 But I want only first 10 rows to be displayed.但我只想显示前 10 行。
What is the equivalent of select top 10 or limit 10 in this scenario.在这种情况下, select top 10limit 10名的等价物是什么。 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();

I think that the method you are looking for is Take我认为您正在寻找的方法是 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();

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.您可能认为只有几行,但如果DBAdmin做错了什么,客户表中可能有 1000 万行。

So use a Request query object to request your data with some boundary condition values set by default.因此,使用 Request 查询 object 来请求您的数据,其中包含一些默认设置的边界条件值。

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:结果 object 模板如下所示:


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM