SearchValues object become better with .NET 9

02/02/2024

SearchValues, which were introduced with .NET 8 will become an upgrade and becomes more usable! Let's see how.

What is SearchValues?

SearchValues is a new type that was introduced with .NET 8. It is a type that is used to represent the values that are used in a search. Here a basic example:

SearchValues<char> searchValues = SearchValues.Create(new[] { 'a', 'e', 'i', 'o', 'u' });

Console.WriteLine(ContainsVowel("Hello, World!")); // Returns true

bool ContainsVowel(ReadOnlySpan<char> text) => text.ContainsAny(searchValues);

Until now we are limited. We can only search for char values. But what if we want to search for string values aka text inside other text? Well, we can't. But with .NET 9 we can! There are new overloads and basically SearchValues is applicable to text as well:

SearchValues<string> Names = SearchValues.Create(
        ["Steven", "Sherlock", "Holmes", "Michael", "Scott"],
        StringComparison.OrdinalIgnoreCase);

const string TextWithNames = "This is Steven and Michael. You know Michael Scott from the office. ";

var index = MemoryExtensions.ContainsAny(TextWithNames, Names);
Console.WriteLine(index); // Returns true
6
An error has occurred. This application may no longer respond until reloaded. Reload x