IEnumerable<>.Count vs IEnumerable.ToList().Count

Viewed 42

I am trying to find if a list is Empty. Whats the most efficient way.

IEnumerable<int> TestProp={get; set;}

this TestProb will be populated by another method. when I try to check if list is empty and I have to do this many times few 100s atleast. Right now I see it as

var cnt=TestProp.ToList().Count>0;

I know IEnumerable will try to find Count property by converting to ICollection but what I am looking here is best performant way for finding non empty list. I somehow feel ToList() is not needed here.

2 Answers

you can write your own extension

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && source.Any();
}

and call

if (TestProp.NotNullOrEmpty())

or you can use

if (TestProp?.Any() == true)

but you must be compare with boolean value so you cannot use like this

if (TestProp?.Any())

because TestProp?.Any() will return Nullable<bool>

In general, the answer is to use .Any() If you want a more complete answer you can find it here

Related