Is there any way to compare strings in a C# LINQ expression similar to SQL's LIKE
operator?
Suppose I have a string list. On this list I want to search a string. In SQL, I could write:
SELECT * FROM DischargePort WHERE PortName LIKE '%BALTIMORE%'
Instead of the above, query want a linq syntax.
using System.Text.RegularExpressions; … var regex = new Regex(sDischargePort, RegexOptions.IgnoreCase); var sPortCode = Database.DischargePorts .Where(p => regex.IsMatch(p.PortName)) .Single().PortCode;
My above LINQ syntax does not work. What have I got wrong?
In LINQ to SQL, we don't have a LIKE operator, but by using contains(), startswith(), and endswith() methods, we can implement LIKE operator functionality in LINQ to SQL.
Advertisements. A set of extension methods forming a query pattern is known as LINQ Standard Query Operators. As building blocks of LINQ query expressions, these operators offer a range of query capabilities like filtering, sorting, projection, aggregation, etc.
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.
LINQ StartsWith , EndsWith , and Contains are case sensitive and return false if two same string s are of different cases, e.g., " STRING " and " string ".
Typically you use String.StartsWith
/EndsWith
/Contains
. For example:
var portCode = Database.DischargePorts .Where(p => p.PortName.Contains("BALTIMORE")) .Single() .PortCode;
I don't know if there's a way of doing proper regular expressions via LINQ to SQL though. (Note that it really does depend on which provider you're using - it would be fine in LINQ to Objects; it's a matter of whether the provider can convert the call into its native query format, e.g. SQL.)
EDIT: As BitKFu says, Single
should be used when you expect exactly one result - when it's an error for that not to be the case. Options of SingleOrDefault
, FirstOrDefault
or First
should be used depending on exactly what's expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With