Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIKE operator in LINQ

Tags:

c#

linq

sql-like

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?

like image 310
shamim Avatar asked Mar 21 '11 06:03

shamim


People also ask

How to do a LIKE in LINQ?

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.

What is LINQ operator?

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.

How do I select a query in LINQ?

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.

Is LINQ case sensitive?

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 ".


1 Answers

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.

like image 148
Jon Skeet Avatar answered Sep 19 '22 02:09

Jon Skeet