如何使用c#和SQL中的LIKE逻辑过滤字符串?
我在C#aka product_name中有一个字符串变量,我想像这样过滤,让它返回true或false:如何使用c#和SQL中的LIKE逻辑过滤字符串?,c#,string,filter,C#,String,Filter,我在C#aka product_name中有一个字符串变量,我想像这样过滤,让它返回true或false: product_name LIKE '%BONUS NAME%' 请问我怎么做 PS:我必须在C#而不是SQL上执行此操作。简单选项:使用String.Contains MSDN页面中的示例 // This example demonstrates the String.Contains() method using System; class Sample { publ
product_name LIKE '%BONUS NAME%'
请问我怎么做
PS:我必须在C#而不是SQL上执行此操作。简单选项:使用String.Contains MSDN页面中的示例
// This example demonstrates the String.Contains() method
using System;
class Sample
{
public static void Main()
{
string s1 = "The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b;
b = s1.Contains(s2);
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);
}
}
/*
This example produces the following results:
Is the string, s2, in the string, s1?: True
*/
更健壮:使用正则表达式库
正则表达式给了您更多的功能,但您可以使用正则表达式运算符“.”和“*”模拟SQL的通配符
string text = "The quick brown fox jumps over the lazy dog";
string pat = @"fox";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
我喜欢使用
IndexOf
方法匹配字符串的一部分:
string input = "This is My FuLl string";
string lookFor = "full";
bool foundIt = input.IndexOf(lookFor, StringComparison.OrdinalIgnoreCase) >= 0;
与Contains
不同,这将打开不区分大小写的匹配
string input = "This is My FuLl string";
string lookFor = "full";
bool foundIt = input.IndexOf(lookFor, StringComparison.OrdinalIgnoreCase) >= 0;