C# Version Of SQL LIKE
Regular expressions allow for everything that LIKE
allows for, and much more, but have a completely different syntax. However, since the rules for LIKE
are so simple(where %
means zero-or-more characters and _
means one character), and both LIKE
arguments and regular expressions are expressed in strings, we can create a regular expression that takes a LIKE
argument (e.g. abc_ef% *usd
) and turn it into the equivalent regular expression (e.g. \Aabc.ef.* \*usd\z
):
@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z"
From that we can build a Like()
method:
public static class MyStringExtensions
{
public static bool Like(this string toSearch, string toFind)
{
return new Regex(@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z", RegexOptions.Singleline).IsMatch(toSearch);
}
}
And hence:
bool willBeTrue = "abcdefg".Like("abcd_fg");
bool willAlsoBeTrue = "abcdefg".Like("ab%f%");
bool willBeFalse = "abcdefghi".Like("abcd_fg");
Like operator in SQL alternative in C#
Here is how the TSQL LIKE keyword works.
using System;
namespace SqlLike
{
class Program
{
static void Main(string[] args)
{
var findMe = "ABCHelloXYZ";
// LIKE '......%'
if (findMe.StartsWith("ABC"))
{
Console.WriteLine("Yay");
}
// LIKE '%......'
if (findMe.EndsWith("XYZ"))
{
Console.WriteLine("Woohoo");
}
// LIKE '%......%'
if (findMe.Contains("Hello"))
{
Console.WriteLine("JackPot!!");
}
Console.ReadLine();
}
}
}
Use SQL LIKE operator in C# LINQ
There are lots of possibilities for Like in Linq:
For LIKE '%abc%';
list.Where(x => x.myTextColumn.Contains('abc'));
For LIKE 'abc%';
list.Where(x => x.myTextColumn.StartWith('abc'));
For LIKE '%abc';
list.Where(x => x.myTextColumn.EndsWith('abc'));
Updates : If you need to add Date comparison as well means you can do like the following:
DateTime date2Compare = new DateTime(2017, 1, 20);
list.Where(x => myDateColumn >= date2Compare && x.myTextColumn.Contains('abc'));
SQL LIKE Equivalent in C#
You could achieve your goal by using regular expressions. See Regex.Match Method.
You can transform your selected string from the dropdown list into a regular expression then use the Match method in your LINQ query.
Regex r = new Regex(String.Format ("Customer {0} has {1} orders", "([^\s]+)", "([^\s]+)"));
This code:
o.CustomField.Contains(searchString)
can then be changed to:
r.Match(o.CustomField).Success
The equivalent of SQL's LIKE and _ wildcard in C#
I wrote this directly in the comment box (so this function may not compile) but you should use regular expressions. Something similar to this should work:
string GetWarehousByGrade222(string grade, string paste)
{
if (grade == "00" || grade == "01" || grade == "02" || grade == "03" || grade == "04") {
if (Regex.IsMatch(paste, "D..G..DG")) return "1GD";
if (Regex.IsMatch(paste, "D..G..DP")) return "1GD";
if (Regex.IsMatch(paste, "D..G..D.")) return "1GO";
// etc...
}
return null;
}
C# Equivalent of SQL Server DataTypes
This is for SQL Server 2005. There are updated versions of the table for SQL Server 2008, SQL Server 2008 R2, SQL Server 2012 and SQL Server 2014.
SQL Server Data Types and Their .NET Framework Equivalents
The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.
SQL Server data type | CLR data type (SQL Server) | CLR data type (.NET Framework) |
---|---|---|
varbinary | SqlBytes, SqlBinary | Byte[] |
binary | SqlBytes, SqlBinary | Byte[] |
varbinary(1), binary(1) | SqlBytes, SqlBinary | byte, Byte[] |
image | None | None |
varchar | None | None |
char | None | None |
nvarchar(1), nchar(1) | SqlChars, SqlString | Char, String, Char[] |
nvarchar | SqlChars, SqlString | String, Char[] |
nchar | SqlChars, SqlString | String, Char[] |
text | None | None |
ntext | None | None |
uniqueidentifier | SqlGuid | Guid |
rowversion | None | Byte[] |
bit | SqlBoolean | Boolean |
tinyint | SqlByte | Byte |
smallint | SqlInt16 | Int16 |
int | SqlInt32 | Int32 |
bigint | SqlInt64 | Int64 |
smallmoney | SqlMoney | Decimal |
money | SqlMoney | Decimal |
numeric | SqlDecimal | Decimal |
decimal | SqlDecimal | Decimal |
real | SqlSingle | Single |
float | SqlDouble | Double |
smalldatetime | SqlDateTime | DateTime |
datetime | SqlDateTime | DateTime |
sql_variant | None | Object |
User-defined type(UDT) | None | user-defined type |
table | None | None |
cursor | None | None |
timestamp | None | None |
xml | SqlXml | None |
What is the equivalent SQL Server type for the C# long type?
The mapping table is clear - BIGINT
is the equivalent of Int64
(which is long
in C#).
How to use the LIKE operator in a C# Command?
Should be:
SELECT * FROM Contacts WHERE Name like @person + '%'
@person
is a parameter - you don't need single quotes around it. You only need to concatenate it with %
, which should have quotes.
Keep in mind:
- You could have kept it
"SELECT * FROM Contacts WHERE Name like @person"
, and have the parameter value contain%
(concatenate in C# is simpler to understand). - You may also want to escape other wildcard characters already in the string:
%
,_
,[
and]
.
using like operator in if operator in C#
Simple way is use the textBox1(where actually filter content going to change) change event
if(!String.IsNullOrEmpty(richTextBox_MWE.Text) && richTextBox_MWE.Text.Trim().Contains(textBox1.Text.Trim()))
{
label5.BackColor = Color.Green;
}
Related Topics
Are There Good Reasons Not to Use an Orm
Dynamic Lang. Runtime VS Reflection
Cannot Load Counter Name Data Because an Invalid Index -Exception
C# Reflection - Load Assembly and Invoke a Method If It Exists
Calling Async Methods from Non-Async Code
Owin's Getexternallogininfoasync Always Returns Null
Improve Wpf Datagrid Performance
How to Store JSON in an Entity Field with Ef Core
How to Add an Ampersand for a Value in a ASP.NET/C# App Config File Value
Login to the Page with Httpwebrequest
Customattribute Reflects HTML Attribute MVC5
When Using a Settings.Settings File in .Net, Where Is the Config Actually Stored
How to Import from Excel to a Dataset Using Microsoft.Office.Interop.Excel