How to simulate regular expressions in LINQ-to-SQL

后端 未结 5 1596
生来不讨喜
生来不讨喜 2020-12-08 12:20

I have a database table with customer account numbers. Within the same table are test accounts that don\'t match the production formatting: say, \'A1111\' is production but

5条回答
  •  执念已碎
    2020-12-08 12:44

    I've had the same problem, but managed to get rid of it. I know it's slow but works, any optimization/bugfix hint will be welcomed :) The code gathers the data first then processes, so you need to filter as much as you can before calling toarray() or buy more ram :)
    hope it helps, enjoy

    Regex rx = LikeToRegEx(emailToMatch);
    
    User[] qry = (from u in context.Users
                  where u.ApplicationName == pApplicationName
                  orderby u.Username
                  select u)
                 .ToArray()
                 .Where(u => rx.IsMatch(u.Email))
                 .ToArray();
    
     // -- LikeToRegEx : Converts SQL like match pattern to a regular expression -- 
     public Regex LikeToRegEx(string likestr, RegexOptions opt = RegexOptions.None)
     {
                likestr = likestr
                         .Replace("*", ".")
                         .Replace("+", ".")
                         .Replace("(", ".")
                         .Replace("[", ".")
                         .Replace("/", ".")
                         .Replace("\\", ".")
                         .Replace("^", ".")
                         .Replace("$", ".")
                         .Replace("_", ".")
                         .Replace("%", ".*");
    
                return new Regex(likestr, opt);
     }
    

    P.S. This is a fast way for processing light data tables, you can improve it by just fetching needed columns for processing and just return ID columns for full access to rows. You can use my last post for a more general heavy duty scenarios. Choice is yours.

提交回复
热议问题