Monday, April 6, 2015

ASP.Net C# Extension Method to compare multiple string values (case insensitive)

A few days ago I posted ASP.Net C# Extension Method to compare string values (case insensitive), which is a simple extension method to compare string values without having to worry about case sensitivity.

Here's an overloaded version of this method that lets you compare a string with multiple values.

Code:
 public static bool IsEqual(this string Value, params string[] CompareValues)   
 {   
      if (Value != null && CompareValues != null)   
      {   
           foreach (string CompareValue in CompareValues)   
           {   
                if (Value.IsEqual(CompareValue))   
                {   
                     return true;   
                }   
           }   
      }   
       
      return false;   
 }   

Example usage:
 foreach(string Action in Actions.Where(x => x.IsEqual("Add", "Update", "Delete")))  
 {  
      // code  
 }  

Again, this is one I use to keep the code a little shorter, and in my opinion more readable, opposed to having to say x == "Add" || x == "Update" || x == "Delete" and having to worry about case-sensitivity, etc.

0 comments: