简体   繁体   中英

How can I use C# contains method with the functionality of sql LIKE condition?

I want to be able to use the contains function the same way the like operator works in sql. So when I call .contains(%This%%%%%%is%%my%string%%) from a list or whatever such as "This is my string " then the function will return true. I've done a lot of searching and it seems like a lot of people would like this function. So how can this be done or how can a custom like function with the same functionality be made?

EDIT Thank you, for the quick response. I was able to use a regular expressions inside of my own custom Like function. Below is the code for anyone else who wants to use something similar to SQL Like. In this code the user would input the databaze value and then spaces in that value are replaced with .* to ignore anything in-between the values.Just like using the % to replace spaces and values in SQL. I can then use .Like on my string value called testValue that I am searching through to return true or false depending on if the words or whatever are in my string. I also added ToUpper to ignore the case. //C# Like function

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace sqllinqstuff
{


class Program
{
    static void Main(string[] args)
    {
        string testValue = "Big RED           Car";

        string databaze = "big red CAR";

        string databaze3 = databaze.Replace("     ", ".*");
        databaze3 = databaze3.Replace(" ", ".*");

        Console.WriteLine(databaze3);
        Console.WriteLine(testValue.Like(databaze3)); 

Console.Read();

    }
}



public static class CaseyStringExtension
{
    public static bool Like(this string str,string value)
    {
        if (!string.IsNullOrEmpty(str))
        {
            Regex r = new Regex(value.ToUpper());
                if (r.IsMatch(str.ToUpper()))
                    return true;

        }

        return false;
    }
}

}

The result of this test will be true.

The way this would be done is with Regex . The syntax is not the same as a SQL LIKE query so there will be a bit of a learning curve. This is a good tutorial site I often reference, it can get you started with the basics.

Translating your original string you asked about, the regex search pattern would be

.*This.*is.*my.*string.*

Once you get good at it you can do searches like this one I helped create for a password complexity checker

(?=^.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])(?=^.*[^\s].*$).*$

The above search looks for a string that has at least 8 characters with at least one lower case letter, one upper case letter, one special character, and no white-space characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM