The nature of your desired result requires that you either make two requests for data, for example, you are now, or buffer non-matches in order to return if no matches are found. A later version will be especially useful in cases where actually obtaining data is a relatively expensive call (for example: querying a database or WCF service). The buffering method will look like this:
static IEnumerable<T> AllIfNone<T>(this IEnumerable<T> source, Func<T, bool> predicate) { //argument checking ignored for sample purposes var buffer = new List<T>(); bool foundFirst = false; foreach (var item in source) { if (predicate(item)) { foundFirst = true; yield return item; } else if (!foundFirst) { buffer.Add(item); } } if (!foundFirst) { foreach (var item in buffer) { yield return item; } } }
The laziness of this method is either Where or ToList , depending on whether the collection contains a match or not. If so, you should do a run like Where . If not, you will get roughly executing a ToList call (with the overhead of all failed filter checks) and iterating the result.
source share