LIKE operator in LINQ

前端 未结 14 1046
一生所求
一生所求 2020-11-27 16:29

Is there any way to compare strings in a C# LINQ expression similar to SQL\'s LIKE operator?

Suppose I have a string list. On this list I want to search

相关标签:
14条回答
  • 2020-11-27 17:03

    Regex? no. But for that query you can just use:

     string filter = "BALTIMORE";
     (blah) .Where(row => row.PortName.Contains(filter)) (blah)
    

    If you really want SQL LIKE, you can use System.Data.Linq.SqlClient.SqlMethods.Like(...), which LINQ-to-SQL maps to LIKE in SQL Server.

    0 讨论(0)
  • 2020-11-27 17:05

    Just add to string object extention methods.

    public static class StringEx
    {
        public static bool Contains(this String str, string[] Arr, StringComparison comp)
        {
            if (Arr != null)
            {
                foreach (string s in Arr)
                {
                    if (str.IndexOf(s, comp)>=0)
                    { return true; }
                }
            }
    
            return false;
        }
    
        public static bool Contains(this String str,string[] Arr)
        {
            if (Arr != null)
            {
                foreach (string s in Arr)
                {
                    if (str.Contains(s))
                    { return true; }
                }
            }
    
            return false;
        }
    }
    

    usage:

    use namespase that contains this class;
    
    var sPortCode = Database.DischargePorts
                .Where(p => p.PortName.Contains(new string [] {"BALTIMORE"},  StringComparison.CurrentCultureIgnoreCase) )
                .Single().PortCode;
    
    0 讨论(0)
提交回复
热议问题