Check if IEnumerable has ANY strings without listing all over the list

I have the following method that returns an IEnumerable type T The implementation of the method is not important except yield return to lazy loading IEnumerable . This is necessary because the result can have millions of elements.

 public IEnumerable<T> Parse() { foreach(...) { yield return parsedObject; } } 

Problem:

I have the following property that can be used to determine if IEnumerable have any elements:

 public bool HasItems { get { return Parse().Take(1).SingleOrDefault() != null; } } 

Perhaps the best way to do this?

+6
source share
2 answers

IEnumerable.Any() will return true if there are any elements in the sequence and false if there are no elements in the sequence. This method will not iterate over the entire sequence (only a maximum of one element), since it will return true if it skips the first element and false if it is not.

+24
source

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 => { // show how many times it happens sideeffect++; return i; }); // will 'enumerate' one item! if(enumerable.Any()) Console.WriteLine("There are items in the list; sideeffect={0}", sideeffect); 

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 
+1
source

Source: https://habr.com/ru/post/946492/


All Articles