Skip to content

Instantly share code, notes, and snippets.

@salesHgabriel
Created February 8, 2023 17:42
Show Gist options
  • Save salesHgabriel/1dd60899e7309d489d7096938e8022d0 to your computer and use it in GitHub Desktop.
Save salesHgabriel/1dd60899e7309d489d7096938e8022d0 to your computer and use it in GitHub Desktop.
Where if extension linq method C#
public static class Where
{
private static string nomeMetodoWhere = "where";
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate, bool condicao)
{
if (source == null)
throw new Exception("source");
if (predicate == null)
throw new Exception("predicate");
if (condicao)
{
var methodCallExpression = Expression.Call(
typeof(Queryable),
nomeMetodoWhere,
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<TSource, int, bool>>(predicate.Body, predicate.Parameters)
);
return source.Provider.CreateQuery<TSource>(methodCallExpression);
}
return source;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int>> predicate, bool condicao)
{
if (source == null)
throw new Exception("source");
if (predicate == null)
throw new Exception("predicate");
if (condicao)
{
var methodCallExpression = Expression.Call(
typeof(Queryable),
nomeMetodoWhere,
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<TSource, int>>(predicate.Body, predicate.Parameters));
return source.Provider.CreateQuery<TSource>(methodCallExpression);
}
return source;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate, bool condicao)
{
if (source == null)
throw new Exception("source");
if (predicate == null)
throw new Exception("predicate");
if (condicao)
{
var methodCallExpression = Expression.Call(
typeof(Queryable),
nomeMetodoWhere,
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<TSource, bool>>(predicate.Body, predicate.Parameters)
);
return source.Provider.CreateQuery<TSource>(methodCallExpression);
}
return source;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment