1

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.

Programmerzzz
  • 1,237
  • 21
  • 48
  • 1
    In many cases `TestProp.Any()` will be the fastest way to check for empty collection. See also https://stackoverflow.com/a/305156/2011071 – Serg Jul 01 '22 at 18:47

2 Answers2

2

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>

Onur Gelmez
  • 1,044
  • 7
  • 9
2

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

Jaden
  • 29
  • 2