Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Specialized;
- using System.Linq;
- using System.Web;
- namespace demo
- {
- class Program
- {
- static void Main(string[] args)
- {
- // create a PagingOptions object from URL
- var parser = new PagingQueryOptionsParser();
- var options = parser.Parse(new Uri("https://localhost/foo?$top=5&$skip=5"));
- // retrieve data as a queryable
- var items = Enumerable.Range(0, 100).AsQueryable();
- // apply paging query options
- var result = options.Apply(items);
- // print result
- System.Console.WriteLine("{0}", string.Join(", ", result));
- }
- }
- public class PagingQueryOptions
- {
- public PagingQueryOptions(int? take, int? skip)
- {
- Take = take;
- Skip = skip;
- }
- public int? Take { get; }
- public int? Skip { get; }
- public IQueryable<T> Apply<T>(IQueryable<T> items)
- {
- // n.b. order of skip and take is important
- if (Skip.HasValue)
- {
- items = items.Skip(Skip.Value);
- }
- if (Take.HasValue)
- {
- items = items.Take(Take.Value);
- }
- return items;
- }
- }
- public class PagingQueryOptionsParser
- {
- public PagingQueryOptions Parse(Uri url)
- {
- var query = HttpUtility.ParseQueryString(url.Query);
- var take = GetSingleIntQueryOption("$top", query);
- var skip = GetSingleIntQueryOption("$skip", query);
- return new PagingQueryOptions(take, skip);
- }
- // get the value of the query option with name <name> and return it as int?
- // return null if the name is not present,
- // throw ArgumentException if value is not a number or the name is given more than once
- // return the value as an Int otherwise
- private static int? GetSingleIntQueryOption(string name, NameValueCollection query)
- {
- var values = query.GetValues(name);
- if (values == null)
- {
- return null;
- }
- if (values.Length > 1)
- {
- throw new ArgumentException($"Invalid query parameter, query option {name} must not appear more than once");
- }
- return Int32.TryParse(values.Single(), out var val) ? val :
- throw new ArgumentException($"Query Option {name}'s value is not a number");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement