All Articles

LINQ Helpers and Extensions

LINQ

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.

LINQ Extensions

First create a class named LinqHelpers, we’ll be adding the extension methods one-by-one to this class.

public static class LinqHelpers     
{

}

IsNullOrEmpty

I often miss the IsNullOrEmpty method for collections as it is there for strings. I use this method extensively for collection validations.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
{
   return collection == null || !collection.Any();
}

FilterNulls

This method can be used to Filter all the nulls within a collection.

public static IEnumerable<T> FilterNulls<T>(this IEnumerable<T> collection)         
{
    return collection.Where(x => x != null);
}

CaseInsensitiveContains

As there is no method in LINQ to check Contains in a case-insensitive manner. This method comes handy.

public static bool CaseInsensitiveContains<T>(this IEnumerable<string> collection, string match) 
{      
     foreach (string item in collection)
     {
          if(item.Equals(match, StringComparison.InvariantCultureIgnoreCase))
          {
            return true;
          }
      }
      return false;
}

TrimAll

This method can be used to trim spaces or any other characters from the strings in a collection.

public static IEnumerable<string> TrimAll<T>(this IEnumerable<string> collection, char trimChar = ' ')         
{
    return collection.Select(x => x.Trim(trimChar));
}

I will keep adding more and more methods in this post in the future.

Please post in the comments any methods you think I should be adding to this post.