Project · Data

Catalog search

Filter a small product catalog and page a stable result.

All C# source files below are loaded together in the playground. Files written by a run live in its virtual directory.

Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var catalog = new[] { new Product("B", "Blue notebook", 7m), new Product("A", "Blue pen", 3m), new Product("C", "Red pen", 4m) };
foreach (var product in Catalog.Search(catalog, "blue", 0, 10)) Console.WriteLine($"{product.Code}:{product.Name}");

Models/Product.cs

public sealed record Product(string Code, string Name, decimal Price);

Search/Catalog.cs

using System;
using System.Collections.Generic;
using System.Linq;
public static class Catalog
{
    public static Product[] Search(IEnumerable<Product> source, string term, int page, int size)
    {
        if (page < 0 || size is < 1 or > 100) throw new ArgumentOutOfRangeException();
        return source.Where(x => x.Name.Contains(term, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Code, StringComparer.Ordinal).Skip(checked(page * size)).Take(size).ToArray();
    }
}

Catalogsearch.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>