Like Howto: count elements from IEnumerable <T> without repeating? a Enumerable means a lazy , readable "list" and, like quantum mechanics, the action of his research changes his state.
See confirmation: https://dotnetfiddle.net/GPMVXH
var sideeffect = 0; var enumerable = Enumerable.Range(1, 10).Select(i => {
enumerable.Any() is the cleanest way to check if there are any items in a list. You can try to do something not lazy, for example if(null != (list = enumerable as ICollection<T>) && list.Any()) return true .
Or your script may allow the use of Enumerator and do a preliminary check before listing:
var e = enumerable.GetEnumerator(); // check first if(!e.MoveNext()) return; // do some stuff, then enumerate the list do { actOn(e.Current); // do stuff with the current item } while(e.MoveNext()); // stop when we don't have anything else
source share