【问题标题】:How do I filter a c# datatable using a rowfilter with multiple asterisks?如何使用带有多个星号的行过滤器过滤 c# 数据表?
【发布时间】:2012-06-23 22:42:21
【问题描述】:
我有一个使用行过滤器的数据表。这是我需要的匹配类型的示例。我只使用星号。
我正在检查的字符串:“你好,你好吗”
过滤器:“*” - 匹配
过滤器:“你好*” - 匹配
过滤器:“你好” - 不匹配
过滤器:“*如何*” - 匹配
过滤器:“你好*你” - 匹配
过滤器:“H*l*w*r*u” - 匹配
当我尝试使用超过 2 个星号时,我收到一个异常,提示“字符串模式无效”。
我该怎么办?
【问题讨论】:
标签:
c#
string
datatable
filtering
【解决方案1】:
尝试使用 % 代替通配符过滤器:
System.Data.DataRow[] y = x.Select("Col2 LIKE 'smith[%]%'");
System.Data.DataRow[] y = x.Select("Col2 = 'smith%'");
【解决方案2】:
行过滤器不能在字符串中间使用*。我会改用这样的东西。
用法:
var rows = dt.AsEnumerable()
.Where(x => x.Field<string>("Name").Like("H*l*w*r*u"));
点赞功能:
public static class Extensions
{
public static bool Like(this string s, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
{
return Regex.IsMatch(s, pattern, options);
}
}