简体   繁体   中英

Skip and Take for nullable / optional parameters

I have an REST API, that has some optional parameters that you can use for pagination. 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?

I don´t understand why you think linq has such a feature. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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