<p>What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type <code>IEnumerable&lt;T&gt;</code> and doesn't have a Count property.</p>

<p>Right now I'm tossing up between this:</p>

<pre><code>if (myList.Count() == 0) { ... }
</code></pre>

<p>and this:</p>

<pre><code>if (!myList.Any()) { ... }
</code></pre>

<p>My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.</p>

<p>That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?</p>

<p><strong>Edit</strong> @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:</p>

<pre><code>public static bool IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; list)
{
    if (list is ICollection&lt;T&gt;) return ((ICollection&lt;T&gt;)list).Count == 0;

    return !list.Any();
}
</code></pre>

[{'answer_id': 41324, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 8, 'selected': True, 'text': '<p>You could do this:</p>\n\n<pre><code>public static Boolean IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n    if (source == null)\n        return true; // or throw an exception\n    return !source.Any();\n}\n</code></pre>\n\n<p><strong>Edit</strong>: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.</p>\n'}, {'answer_id': 41325, 'author': 'crucible', 'author_id': 3717, 'author_profile': 'https://Stackoverflow.com/users/3717', 'pm_score': 3, 'selected': False, 'text': '<p>I just wrote up a quick test, try this:</p>\n\n<pre><code> IEnumerable&lt;Object&gt; myList = new List&lt;Object&gt;();\n\n Stopwatch watch = new Stopwatch();\n\n int x;\n\n watch.Start();\n for (var i = 0; i &lt;= 1000000; i++)\n {\n    if (myList.Count() == 0) x = i; \n }\n watch.Stop();\n\n Stopwatch watch2 = new Stopwatch();\n\n watch2.Start();\n for (var i = 0; i &lt;= 1000000; i++)\n {\n     if (!myList.Any()) x = i;\n }\n watch2.Stop();\n\n Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());\n Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());\n Console.ReadLine();\n</code></pre>\n\n<p>The second is almost three times slower :)</p>\n\n<p>Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.</p>\n\n<p>So I guess it depends on the type of list you\'re using!</p>\n\n<p>(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)</p>\n'}, {'answer_id': 41339, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 2, 'selected': False, 'text': "<p>The second option is much quicker if you have multiple items.</p>\n\n<ul>\n<li><code>Any()</code> returns as soon as 1 item is found.</li>\n<li><code>Count()</code> has to keep going through the entire list.</li>\n</ul>\n\n<p>For instance suppose the enumeration had 1000 items.</p>\n\n<ul>\n<li><code>Any()</code> would check the first one, then return true.</li>\n<li><code>Count()</code> would return 1000 after traversing the entire enumeration.</li>\n</ul>\n\n<p>This is potentially worse if you use one of the predicate overrides - Count() still has to check every single item, even it there is only one match.</p>\n\n<p>You get used to using the Any one - it does make sense and is readable.</p>\n\n<p>One caveat - if you have a List, rather than just an IEnumerable then use that list's Count property.</p>\n"}, {'answer_id': 41357, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>LINQ itself must be doing some serious optimization around the Count() method somehow.</p>\n</blockquote>\n\n<p>Does this surprise you? I imagine that for <code>IList</code> implementations, <code>Count</code> simply reads the number of elements directly while <code>Any</code> has to query the <code>IEnumerable.GetEnumerator</code> method, create an instance and call <code>MoveNext</code> at least once.</p>\n\n<p>/EDIT @Matt:</p>\n\n<blockquote>\n  <p>I can only assume that the Count() extension method for IEnumerable is doing something like this:</p>\n</blockquote>\n\n<p>Yes, of course it does. This is what I meant. Actually, it uses <code>ICollection</code> instead of <code>IList</code> but the result is the same.</p>\n'}, {'answer_id': 41365, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 2, 'selected': False, 'text': "<p>@Konrad what surprises me is that in my tests, I'm passing the list into a method that accepts <code>IEnumerable&lt;T&gt;</code>, so the runtime can't optimize it by calling the Count() extension method for <code>IList&lt;T&gt;</code>.</p>\n\n<p>I can only assume that the Count() extension method for IEnumerable is doing something like this:</p>\n\n<pre><code>public static int Count&lt;T&gt;(this IEnumerable&lt;T&gt; list)\n{\n    if (list is IList&lt;T&gt;) return ((IList&lt;T&gt;)list).Count;\n\n    int i = 0;\n    foreach (var t in list) i++;\n    return i;\n}\n</code></pre>\n\n<p>... in other words, a bit of runtime optimization for the special case of <code>IList&lt;T&gt;</code>.</p>\n\n<p>/EDIT @Konrad +1 mate - you're right about it more likely being on <code>ICollection&lt;T&gt;</code>.</p>\n"}, {'answer_id': 1620712, 'author': 'Jonny Dee', 'author_id': 196164, 'author_profile': 'https://Stackoverflow.com/users/196164', 'pm_score': -1, 'selected': False, 'text': '<p>This extension method works for me:</p>\n\n<pre><code>public static bool IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)\n{\n    try\n    {\n        enumerable.First();\n        return false;\n    }\n    catch (InvalidOperationException)\n    {\n        return true;\n    }\n}\n</code></pre>\n'}, {'answer_id': 1623097, 'author': 'Jonny Dee', 'author_id': 196432, 'author_profile': 'https://Stackoverflow.com/users/196432', 'pm_score': 1, 'selected': False, 'text': "<p>Ok, so what about this one?</p>\n\n<pre><code>public static bool IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)\n{\n    return !enumerable.GetEnumerator().MoveNext();\n}\n</code></pre>\n\n<p>EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards</p>\n"}, {'answer_id': 1938747, 'author': 'ChulioMartinez', 'author_id': 63865, 'author_profile': 'https://Stackoverflow.com/users/63865', 'pm_score': 1, 'selected': False, 'text': '<p>Another idea:</p>\n\n<pre><code>if(enumerable.FirstOrDefault() != null)\n</code></pre>\n\n<p>However I like the Any() approach more.</p>\n'}, {'answer_id': 3495249, 'author': 'Dasmowenator', 'author_id': 367544, 'author_profile': 'https://Stackoverflow.com/users/367544', 'pm_score': 3, 'selected': False, 'text': '<p><code>List.Count</code> is O(1) according to Microsoft\'s documentation:<br>\n<a href="http://msdn.microsoft.com/en-us/library/27b47ht3.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/27b47ht3.aspx</a>  </p>\n\n<p>so just use <code>List.Count == 0</code> it\'s much faster than a query</p>\n\n<p>This is because it has a data member called Count which is updated any time something is added or removed from the list, so when you call <code>List.Count</code> it doesn\'t have to iterate through every element to get it, it just returns the data member.</p>\n'}, {'answer_id': 3576549, 'author': 'Dan Tao', 'author_id': 105570, 'author_profile': 'https://Stackoverflow.com/users/105570', 'pm_score': 4, 'selected': False, 'text': '<p>I would make one small addition to the code you seem to have settled on: check also for <code>ICollection</code>, as this is implemented even by some non-obsolete generic classes as well (i.e., <code>Queue&lt;T&gt;</code> and <code>Stack&lt;T&gt;</code>). I would also use <code>as</code> instead of <code>is</code> as it\'s more idiomatic and <a href="http://www.codeproject.com/KB/cs/csharpcasts.aspx" rel="noreferrer">has been shown to be faster</a>.</p>\n\n<pre><code>public static bool IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; list)\n{\n    if (list == null)\n    {\n        throw new ArgumentNullException("list");\n    }\n\n    var genericCollection = list as ICollection&lt;T&gt;;\n    if (genericCollection != null)\n    {\n        return genericCollection.Count == 0;\n    }\n\n    var nonGenericCollection = list as ICollection;\n    if (nonGenericCollection != null)\n    {\n        return nonGenericCollection.Count == 0;\n    }\n\n    return !list.Any();\n}\n</code></pre>\n'}, {'answer_id': 6958074, 'author': 'gandarez', 'author_id': 833531, 'author_profile': 'https://Stackoverflow.com/users/833531', 'pm_score': 0, 'selected': False, 'text': '<p>If I check with Count() Linq executes a "SELECT COUNT(*).." in the database, but I need to check if the results contains data, I resolved to introducing FirstOrDefault() instead of Count();</p>\n\n<p>Before</p>\n\n<pre><code>var cfop = from tabelaCFOPs in ERPDAOManager.GetTable&lt;TabelaCFOPs&gt;()\n\nif (cfop.Count() &gt; 0)\n{\n    var itemCfop = cfop.First();\n    //....\n}\n</code></pre>\n\n<p>After</p>\n\n<pre><code>var cfop = from tabelaCFOPs in ERPDAOManager.GetTable&lt;TabelaCFOPs&gt;()\n\nvar itemCfop = cfop.FirstOrDefault();\n\nif (itemCfop != null)\n{\n    //....\n}\n</code></pre>\n'}, {'answer_id': 8527081, 'author': 'Holt Mansfield', 'author_id': 522598, 'author_profile': 'https://Stackoverflow.com/users/522598', 'pm_score': 1, 'selected': False, 'text': '<p>This was critical to get this to work with Entity Framework:</p>\n\n<pre><code>var genericCollection = list as ICollection&lt;T&gt;;\n\nif (genericCollection != null)\n{\n   //your code \n}\n</code></pre>\n'}, {'answer_id': 9770656, 'author': 'suneelsarraf', 'author_id': 1124234, 'author_profile': 'https://Stackoverflow.com/users/1124234', 'pm_score': 0, 'selected': False, 'text': '<pre><code>private bool NullTest&lt;T&gt;(T[] list, string attribute)\n\n    {\n        bool status = false;\n        if (list != null)\n        {\n            int flag = 0;\n            var property = GetProperty(list.FirstOrDefault(), attribute);\n            foreach (T obj in list)\n            {\n                if (property.GetValue(obj, null) == null)\n                    flag++;\n            }\n            status = flag == 0 ? true : false;\n        }\n        return status;\n    }\n\n\npublic PropertyInfo GetProperty&lt;T&gt;(T obj, string str)\n\n    {\n        Expression&lt;Func&lt;T, string, PropertyInfo&gt;&gt; GetProperty = (TypeObj, Column) =&gt; TypeObj.GetType().GetProperty(TypeObj\n            .GetType().GetProperties().ToList()\n            .Find(property =&gt; property.Name\n            .ToLower() == Column\n            .ToLower()).Name.ToString());\n        return GetProperty.Compile()(obj, str);\n    }\n</code></pre>\n'}, {'answer_id': 10409651, 'author': 'Milad Sadeghi', 'author_id': 1369436, 'author_profile': 'https://Stackoverflow.com/users/1369436', 'pm_score': -1, 'selected': False, 'text': '<pre><code>List&lt;T&gt; li = new List&lt;T&gt;();\n(li.First().DefaultValue.HasValue) ? string.Format("{0:yyyy/MM/dd}", sender.First().DefaultValue.Value) : string.Empty;\n</code></pre>\n'}, {'answer_id': 12237400, 'author': 'devuxer', 'author_id': 129164, 'author_profile': 'https://Stackoverflow.com/users/129164', 'pm_score': 0, 'selected': False, 'text': "<p>Here's my implementation of Dan Tao's answer, allowing for a predicate:</p>\n\n<pre><code>public static bool IsEmpty&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate)\n{\n    if (source == null) throw new ArgumentNullException();\n    if (IsCollectionAndEmpty(source)) return true;\n    return !source.Any(predicate);\n}\n\npublic static bool IsEmpty&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)\n{\n    if (source == null) throw new ArgumentNullException();\n    if (IsCollectionAndEmpty(source)) return true;\n    return !source.Any();\n}\n\nprivate static bool IsCollectionAndEmpty&lt;TSource&gt;(IEnumerable&lt;TSource&gt; source)\n{\n    var genericCollection = source as ICollection&lt;TSource&gt;;\n    if (genericCollection != null) return genericCollection.Count == 0;\n    var nonGenericCollection = source as ICollection;\n    if (nonGenericCollection != null) return nonGenericCollection.Count == 0;\n    return false;\n}\n</code></pre>\n"}, {'answer_id': 30056312, 'author': 'user3149517', 'author_id': 3149517, 'author_profile': 'https://Stackoverflow.com/users/3149517', 'pm_score': -1, 'selected': False, 'text': "<p><code>myList.ToList().Count == 0</code>. That's all</p>\n"}]
['https://Stackoverflow.com/questions/41319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/615/']