For performance reasons many of my services are returning IQueryables right now, so the caller can decide what elements to filter before they get materialized. For design reasons (interfaces etc.) I'd rather like to return IEnumerables but that sure removes the advantages of IQueryables: materialization of the complete result set plus no -Async methods.
I've started writing some extension methods that prefer IQueryable over IEnumerable, e.g.:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Expression<Func<TSource, bool>> predicate)
=> source is IQueryable<TSource> ? Queryable.Where(source as IQueryable<TSource>, predicate) : Enumerable.Where(source, predicate.Compile());
public static Task<TSource[]> ToArrayAsync<TSource>(this IEnumerable<TSource> source)
=> (source as IQueryable<TSource>)?.ToArrayAsync() ?? Task.FromResult(source.ToArray());
I can't be the only one thinking about this. Any improvements for these methods? Is there already a good collection / solution out there? Or is this a bad design? So please tell me reasons.
Thank you!
IQueryable
, why would you want to return anIEnumerable
? It will only make less obvious what's going on.