Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's the code from <a href="https://stackoverflow.com/a/5047373/4794">Marc Gravell's answer</a>, along with an example of using it.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; public static class Utils { public static bool IsAny&lt;T&gt;(this IEnumerable&lt;T&gt; data) { return data != null &amp;&amp; data.Any(); } } class Program { static void Main(string[] args) { IEnumerable&lt;string&gt; items; //items = null; //items = new String[0]; items = new String[] { "foo", "bar", "baz" }; /*** Example Starts Here ***/ if (items.IsAny()) { foreach (var item in items) { Console.WriteLine(item); } } else { Console.WriteLine("No items."); } } } </code></pre> <p>As he says, not all sequences are repeatable, so that code may sometimes cause problems, because <code>IsAny()</code> starts stepping through the sequence. I suspect what <a href="https://stackoverflow.com/a/5047375/4794">Robert Harvey's answer</a> meant was that you often don't need to check for <code>null</code> <em>and</em> empty. Often, you can just check for null and then use <code>foreach</code>.</p> <p>To avoid starting the sequence twice and take advantage of <code>foreach</code>, I just wrote some code like this:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { IEnumerable&lt;string&gt; items; //items = null; //items = new String[0]; items = new String[] { "foo", "bar", "baz" }; /*** Example Starts Here ***/ bool isEmpty = true; if (items != null) { foreach (var item in items) { isEmpty = false; Console.WriteLine(item); } } if (isEmpty) { Console.WriteLine("No items."); } } } </code></pre> <p>I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that <code>IsAny(items)</code> will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload