---
title: "Sort full-text search results by price in C#"
url: https://recursiveai.org/oneindex/cookbook/sort-search-results-by-price/
description: "Sort C# full-text search results by a numeric price field before paging, with a stable tie-breaker for equal prices and a rule for missing values."
version: "0.4.0-preview.2"
---

# Sort full-text search results by price in C#

**OneIndex** is a free, open-source search library for .NET from Recursive AI. MIT or Apache-2.0, preview, runs in-process.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneIndex) · [GitHub](https://github.com/recursive-ai-oss/oneindex-csharp) · [Docs](https://recursiveai.org/oneindex/docs/) · [Download example (.zip)](https://recursiveai.org/oneindex/cookbook/sort-search-results-by-price/sort-search-results-by-price.zip)

Use `OrderBy` to sort matching products by price instead of relevance.

```shell
dotnet add package RecursiveAI.OneIndex --prerelease
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneIndex;
using var index = MakeIndex();
foreach (var hit in index.Search("mug")
    .OrderBy(x => x.Cents))
    Console.WriteLine(hit.Document.Cents);

SearchIndex<Product> MakeIndex()
{
    var index = SearchIndex.InMemory<Product>();
    index.Upsert([
        new() { Id = "b", Cents = 1200 },
        new() { Id = "a", Cents = 900 }
    ]);
    index.Commit();
    return index;
}

public class Product
{
    [SearchId]
    public string Id { get; set; } = "";
    [FullText]
    public string Name { get; set; } = "Mug";
    [Sortable] public int Cents { get; set; }
}
```

Prints the prices in cents, lowest first.

```text
900
1200
```

Any `[Sortable]` numeric field sorts the same way: integers (`sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`) and fractional numbers (`float`, `double`). Dates sort by timestamp.

Unzip [the example](https://recursiveai.org/oneindex/cookbook/sort-search-results-by-price/sort-search-results-by-price.zip), then `dotnet run`.

## The full program

The download searches five products: four mugs, including two with the same price and one without a price, and a plate that doesn’t match. The query asks for the three cheapest matches. The download pins OneIndex 0.4.0-preview.2.

```csharp
using OneIndex;

using var index = SearchIndex.InMemory<Product>();
index.Upsert([
    new() { Id = "b", Name = "Travel mug", Cents = 900 },
    new() { Id = "c", Name = "Ceramic mug", Cents = 1200 },
    new() { Id = "a", Name = "Steel mug", Cents = 900 },
    new() { Id = "d", Name = "Mystery mug" },
    new() { Id = "e", Name = "Plate", Cents = 500 }
]);
index.Commit();

var results = index.Search("mug")
    .OrderBy(x => x.Cents)
    .Take(3).Execute();
Console.WriteLine($"Matches: {results.TotalHits}");
foreach (var hit in results)
    Console.WriteLine($"{hit.Id}: {hit.Document.Cents} cents");

public class Product
{
    [SearchId] public string Id { get; set; } = "";
    [FullText] public string Name { get; set; } = "";
    [Sortable] public int? Cents { get; set; }
}
```

`dotnet run` prints:

```text
Matches: 4
a: 900 cents
b: 900 cents
c: 1200 cents
```

If the property has no sortable column, `OrderBy` throws `ArgumentException`; mark the numeric property `[Sortable]` before building the index.

## Variations

To show the highest prices first, replace the query and print loop in the download with this. Missing prices still go last.

```csharp
var results = index.Search("mug")
    .OrderByDescending(x => x.Cents).Take(4);
foreach (var hit in results)
{
    var cents = hit.Document.Cents;
    Console.WriteLine(cents is int price
        ? $"{hit.Id}: {price} cents"
        : $"{hit.Id}: no price");
}
```

```text
c: 1200 cents
a: 900 cents
b: 900 cents
d: no price
```

## Related recipes

[Full-text search](https://recursiveai.org/oneindex/cookbook/full-text-search-csharp/) · [Page search results with a cursor](https://recursiveai.org/oneindex/cookbook/paginate-search-results-with-cursor/)

## The short answer

Mark the numeric price property `[Sortable]` and call `.OrderBy(x => x.Cents)` on the full-text query before taking a page of hits. Text determines which products match. Price determines which of those products comes first. In the example, an equally cheap product with ID `a` sorts before `b` even though it was inserted later.

## How do you sort full-text search results by a numeric field?

Use separate fields for the text users search and the number they sort on. In the download, `[FullText]` makes `Name` searchable, while `[Sortable]` keeps `Cents` in a column for numeric comparison. The search doesn’t parse prices out of product names or sort a formatted display price. If you index `900` and `1200` as strings, their first characters put `"1200"` ahead of `"900"` in text order; the numeric column gives the intended order. Format the number for display after retrieving the hits.

Set the order on the query itself rather than sorting the page after it comes back. In the example, a cheaper plate is not a candidate because it doesn’t match “mug.” The query orders all four mugs and then selects three, so `TotalHits` is four. Sorting just the three hits returned by a relevance query could miss a cheaper mug outside that page. In OneIndex, a sort without a score key doesn’t compute relevance scores; the hit’s `Score` is zero even if its text matches.

## What happens when two search results have the same price?

If you add `ThenBy`, that key breaks ties. For example, if `Stock` is another `[Sortable]` numeric property, this puts lower stock first among products with the same price:

```csharp
var results = index.Search("mug").OrderBy(x => x.Cents).ThenBy(x => x.Stock);
```

Without `ThenBy`, OneIndex compares the document identifiers in UTF-8 byte order. That’s why the two 900-cent products come out as `a`, then `b`, even when you switch to descending price. The ID tie-break also keeps the order across segment merges, which can change internal document numbers.

A missing price is different from a zero price. The example uses `int?`, so an unpriced product has no numeric value and sorts last in either direction. Use zero only when you want the product treated as free. The [sorting docs](https://recursiveai.org/oneindex/docs/sorting/) describe how to request missing values first and how the same tie-break works with cursor paging.
