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:
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


Author: Herman Schoenfeld