LIKE operator in LINQ

前端 未结 14 1138
一生所求
一生所求 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: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;
    

提交回复
热议问题