Created
December 2, 2011 13:03
-
-
Save nekman/1423177 to your computer and use it in GitHub Desktop.
C# Filter extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Utils.Extensions | |
{ | |
public static class FilterExtensions | |
{ | |
/// <summary> | |
/// Remove null values from the collection. | |
/// </summary> | |
/// <typeparam name="TSource">The type of the source.</typeparam> | |
/// <param name="items">The items.</param> | |
/// <returns></returns> | |
public static IList<TSource> Filter<TSource>(this IList<TSource> items) where TSource : class | |
{ | |
return FilterInternal(items, item => item != null).ToList(); | |
} | |
/// <summary> | |
/// Remove null values from the collection. | |
/// </summary> | |
/// <typeparam name="TSource">The type of the source.</typeparam> | |
/// <param name="items">The items.</param> | |
/// <returns></returns> | |
public static IEnumerable<TSource> Filter<TSource>(this IEnumerable<TSource> items) where TSource : class | |
{ | |
return FilterInternal(items, item => item != null); | |
} | |
/// <summary> | |
/// Remove items from the collection that dosen't match the given predicate. | |
/// </summary> | |
/// <typeparam name="TSource">The type of the source.</typeparam> | |
/// <param name="items">The items.</param> | |
/// <param name="predicate">The predicate.</param> | |
/// <returns></returns> | |
public static IList<TSource> Filter<TSource>(this IList<TSource> items, Func<TSource, bool> predicate) where TSource : class | |
{ | |
return FilterInternal(items, predicate).ToList(); | |
} | |
/// <summary> | |
/// Remove items from the collection that dosen't match the given predicate. | |
/// </summary> | |
/// <typeparam name="TSource">The type of the source.</typeparam> | |
/// <param name="items">The items.</param> | |
/// <param name="predicate">The predicate.</param> | |
/// <returns></returns> | |
public static IEnumerable<TSource> Filter<TSource>(this IEnumerable<TSource> items, Func<TSource, bool> predicate) where TSource : class | |
{ | |
return FilterInternal(items, predicate).ToList(); | |
} | |
private static IEnumerable<TSource> FilterInternal<TSource>(IEnumerable<TSource> items, Func<TSource, bool> predicate) where TSource : class | |
{ | |
if (items == null) | |
{ | |
throw new ArgumentNullException("items"); | |
} | |
if (predicate == null) | |
{ | |
throw new ArgumentNullException("predicate"); | |
} | |
return items.Where(predicate); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment