Tuesday, April 7, 2015

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

Here is an extension method to see if a string starts with 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 StartsWithValue(this string Value, string CompareValue)  
 {  
      bool ReturnValue = false;  
   
      if (Value != null && CompareValue != null)  
      {  
           ReturnValue = Value.Trim().StartsWith(CompareValue.Trim(), StringComparison.OrdinalIgnoreCase);  
      }  
   
      return ReturnValue;  
 }  
   
 public static bool StartsWithValue(this string Value, params string[] CompareValues)  
 {  
      if (Value != null && CompareValues != null)  
      {  
           foreach (string CompareValue in CompareValues)  
           {  
                if (Value.StartsWithValue(CompareValue))  
                {  
                     return true;  
                }  
           }  
      }  
   
      return false;  
 }  

Example usage:
 public bool IsDEV  
 {  
      get  
      {  
           return Request.Url.Host.StartsWithValue("dev.");  
      }  
 }  
 public List<String> Prefixes = new List<String>() { "lbl", "btn" };  
   
 foreach (Control Control in PageControls.Where(x => x.ID.StartsWithValue(Prefixes.ToArray())))  
 {  
      // code   
 }  

0 comments: