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
Regex? no. But for that query you can just use:
string filter = "BALTIMORE";
(blah) .Where(row => row.PortName.Contains(filter)) (blah)
If you really want SQL LIKE
, you can use System.Data.Linq.SqlClient.SqlMethods.Like(...), which LINQ-to-SQL maps to LIKE
in SQL Server.
Just add to string object extention methods.
public static class StringEx
{
public static bool Contains(this String str, string[] Arr, StringComparison comp)
{
if (Arr != null)
{
foreach (string s in Arr)
{
if (str.IndexOf(s, comp)>=0)
{ return true; }
}
}
return false;
}
public static bool Contains(this String str,string[] Arr)
{
if (Arr != null)
{
foreach (string s in Arr)
{
if (str.Contains(s))
{ return true; }
}
}
return false;
}
}
usage:
use namespase that contains this class;
var sPortCode = Database.DischargePorts
.Where(p => p.PortName.Contains(new string [] {"BALTIMORE"}, StringComparison.CurrentCultureIgnoreCase) )
.Single().PortCode;