LIKE operator in LINQ

shamim picture shamim · Mar 21, 2011 · Viewed 247.9k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · Mar 21, 2011

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.