C# LINQ: how to handle wildcard search?

让人想犯罪 __ 提交于 2019-12-08 05:02:32

问题


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)

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?

Thank you very much


回答1:


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));
    }


来源:https://stackoverflow.com/questions/18814084/c-sharp-linq-how-to-handle-wildcard-search

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!