यह स्निपेट एसक्यूएल के व्यवहार और वाक्यविन्यास की नकल करेगा।
public static bool IsSqlLikeMatch(string input, string pattern)
{
/* Turn "off" all regular expression related syntax in
* the pattern string. */
pattern = Regex.Escape(pattern);
/* Replace the SQL LIKE wildcard metacharacters with the
* equivalent regular expression metacharacters. */
pattern = pattern.Replace("%", ".*?").Replace("_", ".");
/* The previous call to Regex.Escape actually turned off
* too many metacharacters, i.e. those which are recognized by
* both the regular expression engine and the SQL LIKE
* statement ([...] and [^...]). Those metacharacters have
* to be manually unescaped here. */
pattern = pattern.Replace(@"\[", "[").Replace(@"\]", "]").Replace(@"\^", "^");
return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
}
एक साथ मारपीट की विस्तार विधि है कि IEnumerable<T>.Where
विधि की तरह काम करेगा:: आप एक Linq बयान भीतर उपयोग के लिए यह लपेट कर सकते हैं अपने खुद की एक लैम्ब्डा या विस्तार विधि में
public static IEnumerable<T> Like<T>(this IEnumerable<T> source, Func<T, string> selector, string pattern)
{
return source.Where(t => IsSqlLikeMatch(selector(t), pattern));
}
कौन सा में होगा बारी तुम इतनी तरह अपने बयान फ़ॉर्मेट करने के लिए अनुमति देते हैं:
string pattern = "%ine%e";
var res = list.Like(s => s, pattern);
संपादित एक इंप्रोव एड कार्यान्वयन, किसी को भी ठोकर मारना चाहिए और इस कोड का उपयोग करना चाहते हैं। यह प्रत्येक आइटम के बजाय एक बार regex को परिवर्तित और संकलित करता है और ऊपर से regex करने के लिए रूपांतरण कुछ बग है।
public static class LikeExtension
{
public static IEnumerable<T> Like<T>(this IEnumerable<T> source, Func<T, string> selector, string pattern)
{
var regex = new Regex(ConvertLikeToRegex(pattern), RegexOptions.IgnoreCase);
return source.Where(t => IsRegexMatch(selector(t), regex));
}
static bool IsRegexMatch(string input, Regex regex)
{
if (input == null)
return false;
return regex.IsMatch(input);
}
static string ConvertLikeToRegex(string pattern)
{
StringBuilder builder = new StringBuilder();
// Turn "off" all regular expression related syntax in the pattern string
// and add regex begining of and end of line tokens so '%abc' and 'abc%' work as expected
builder.Append("^").Append(Regex.Escape(pattern)).Append("$");
/* Replace the SQL LIKE wildcard metacharacters with the
* equivalent regular expression metacharacters. */
builder.Replace("%", ".*").Replace("_", ".");
/* The previous call to Regex.Escape actually turned off
* too many metacharacters, i.e. those which are recognized by
* both the regular expression engine and the SQL LIKE
* statement ([...] and [^...]). Those metacharacters have
* to be manually unescaped here. */
builder.Replace(@"\[", "[").Replace(@"\]", "]").Replace(@"\^", "^");
// put SQL LIKE wildcard literals back
builder.Replace("[.*]", "[%]").Replace("[.]", "[_]");
return builder.ToString();
}
}
वाह! दूसरों की तुलना में इसका सबसे बढ़िया जवाब! आपका बहुत बहुत धन्यवाद –