C#LINQ:如何处理通配符搜索? [英] C# LINQ: how to handle wildcard search?
本文介绍了C#LINQ:如何处理通配符搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要这样的搜索功能:
函数接受多种类型的通配符的所有字符串:
I need a search function like this: The function accepts all strings with many types of wildcards:
* or % >>> can replace one or more characters
# >>> used to replace a number
@ >>> used to replace an alphabet
? >>> used to replace a character (can be both number and alphabet)
据我所知,在LINQ有搜索字串3个功能:StartsWith,和的endsWith包含。 SQL查询中,有2种类型的LIKE:%为一个或多个字符和_对于只有一个字符。
所以,我怎样才能解决这个问题?
As I know, in LINQ there are 3 functions for searching strings: StartsWith, EndsWith and Contains. In SQL query, there are 2 types of LIKE: % for one or more characters and _ for only one character. So, how can I solve this problem?
非常感谢你。
推荐答案
您可以使用正则表达式,并与正则表达式的表达式替换通配符。这里有一个例子
You could use regex and replace the wild cards with regex expressions. Here is an example.
IEnumerable<string> Search(IEnumerable<string> data, string q)
{
string regexSearch = q
.Replace("*", ".+")
.Replace("%", ".+")
.Replace("#", "\\d")
.Replace("@", "[a-zA-Z]")
.Replace("?", "\\w");
Regex regex = new Regex(regexSearch);
return data
.Where(s => regex.IsMatch(s));
}
这篇关于C#LINQ:如何处理通配符搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文