davenewza davenewza - 3 months ago 17
C# Question

Check if IEnumerable has ANY rows without enumerating over the entire list

I have the following method which returns an

IEnumerable
of type
T
. The implementation of the method is not important, apart from the
yield return
to lazy load the
IEnumerable
. This is necessary as the result could have millions of items.

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


Problem:

I have the following property which can be used to determine if the
IEnumerable
will have any items:

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


Is there perhaps a better way to do this?

Answer

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 the entire sequence (only maximum one element) since it will return true if it makes it past the first element and false if it does not.

Comments