Skip to content

Instantly share code, notes, and snippets.

@kcargile
Created August 7, 2012 21:07
Show Gist options
  • Save kcargile/3289376 to your computer and use it in GitHub Desktop.
Save kcargile/3289376 to your computer and use it in GitHub Desktop.
.NET IEnumerable<T> extension method to perform LINQ where filtering only when a certain condition is met (e.g. a "where-if").
using System;
using System.Collections.Generic;
using System.Linq;
namespace Extensions
{
public static class IEnumerableExtensions
{
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
{
return source.Where(predicate);
}
return source;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment