Match prefixes, suffixes and substrings in LINQ

StartsWith("log") matches a prefix. EndsWith("log") matches a suffix. Contains("log") finds a substring anywhere in the value.

Those relationships correspond conceptually to SQL LIKE 'log%', LIKE '%log' and LIKE '%log%', respectively. The comparison rules still depend on whether the query runs in memory or in a database.

Match literal text in memory

In a .NET console project, run this Program.cs:

C#
string[] names = ["logbook", "catalog", "mylogfile", "notes"];
Console.WriteLine(string.Join(", ", names.Where(x => x.StartsWith("log", StringComparison.Ordinal))));
Console.WriteLine(string.Join(", ", names.Where(x => x.EndsWith("log", StringComparison.Ordinal))));
Console.WriteLine(string.Join(", ", names.Where(x => x.Contains("log", StringComparison.Ordinal))));

Expect logbook, then catalog, then logbook, catalog, mylogfile on separate lines.

Use SQL patterns intentionally

For an EF Core SQL Server query, supported string operations translate through the provider. EF.Functions.Like(x.Name, "L_n%") instead accepts a SQL pattern where underscore matches one character and percent matches a sequence. User-entered percent and underscore characters need an escaping policy if they should be literal.

Do not assume StringComparison overloads translate to SQL, or that the database collation matches ordinal C# comparisons. Choose the intended database collation and inspect generated SQL. Leading-wildcard searches can also require scanning substantially more data than a selective prefix lookup.

Official references

Function Mappings - Microsoft SQL Server Database Provider - EF Core
Function Mappings of the Microsoft SQL Server database provider
https://learn.microsoft.com/en-us/ef/core/providers/sql-server/functions
SQL Server provider function mappings
Best Practices for Comparing Strings in .NET - .NET
Learn how to compare strings effectively in .NET applications.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings
String comparison guidance

Author: Herman Schoenfeld