[英]Skip and Take for nullable / optional parameters
I have an REST API, that has some optional parameters that you can use for pagination. 我有一个REST API,其中包含一些可用于分页的可选参数。 Since there nullable, i wrote this sequence of code
由于那里可以为空,所以我写了这段代码
public async Task<DataResult<List<ItemDTO>>> GetItem( int? skip, int? top)
{
var result = await _itemRepository.FilterManyAsync();
if (skip.HasValue)
result.Entities = result.Entities.Skip(skip.Value);
if (top.HasValue)
result.Entities = result.Entities.Take(top.Value);
}
But aren't there elegant ways to do this by LINQ? 但是LINQ是否没有优雅的方法来做到这一点?
I don´t understand why you think linq has such a feature. 我不明白您为什么认为linq具有这种功能。 You should of course first check if your parameter has a value, and if so do the operation, in your case skip or take.
当然,您应该首先检查您的参数是否具有值,如果是这样的话,请跳过或采用该值。
However you could create your own extension for this: 但是,您可以为此创建自己的扩展名:
IEnumerable<T> SkipOrAll(this IEnumerable<T> src, int? skip)
{
return skip.HasValue ? src.Skip(skip) : src;
}
and equivalent for TakeOrAll
: 等效于
TakeOrAll
:
IEnumerable<T> TakeOrAll(this IEnumerable<T> src, int? take)
{
return take.HasValue ? src.Take(take) : src;
}
This can easily be called as this: 可以很容易地这样称呼它:
var result = source.SkipOrAll(skip).TakeOrAll(take);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.