Monday, April 6, 2015

ASP.Net C# Extension Method to see if a string CONTAINS a value (case insensitive)

Here is another simple extension method to see if a string contains a value, and it's case insensitive. There's also an overloaded version of the method to allow you to check multiple values at once.

Code:
 public static bool ContainsValue(this string Value, string CompareValue)  
 {  
      bool ReturnValue = false;  
        
      if (Value != null && CompareValue != null)  
      {  
           ReturnValue = Value.Trim().IndexOf(CompareValue.Trim(), StringComparison.OrdinalIgnoreCase) >= 0;  
      }  
   
      return ReturnValue;  
 }  
   
 public static bool ContainsValue(this string Value, params string[] CompareValues)  
 {  
      if (Value != null && CompareValues != null)  
      {  
           foreach (string CompareValue in CompareValues)  
           {  
                if (Value.ContainsValue(CompareValue))  
                {  
                     return true;  
                }  
           }  
      }  
   
      return false;  
 }  

Example usage:
 if (WebControl.CssClass.ContainsValue("class1", "class2"))  
 {  
      // code  
 }  


0 comments: