How to check if IEnumerable is null or empty?

前端 未结 22 1025
梦如初夏
梦如初夏 2020-11-27 12:33

I love string.IsNullOrEmpty method. I\'d love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection he

22条回答
  •  攒了一身酷
    2020-11-27 13:05

    Here's the code from Marc Gravell's answer, along with an example of using it.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public static class Utils
    {
        public static bool IsAny(this IEnumerable data)
        {
            return data != null && data.Any();
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable 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.");
            }
        }
    }
    

    As he says, not all sequences are repeatable, so that code may sometimes cause problems, because IsAny() starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check for null and empty. Often, you can just check for null and then use foreach.

    To avoid starting the sequence twice and take advantage of foreach, I just wrote some code like this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable 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.");
            }
        }
    }
    

    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 IsAny(items) 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.)

提交回复
热议问题