How to check if IEnumerable is null or empty?

前端 未结 22 1088
梦如初夏
梦如初夏 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:29

    The way I do it, taking advantage of some modern C# features:

    Option 1)

    public static class Utils {
        public static bool IsNullOrEmpty(this IEnumerable list) {
            return !(list?.Any() ?? false);
        }
    }
    

    Option 2)

    public static class Utils {
        public static bool IsNullOrEmpty(this IEnumerable list) {
            return !(list?.Any()).GetValueOrDefault();
        }
    }
    

    And by the way, never use Count == 0 or Count() == 0 just to check if a collection is empty. Always use Linq's .Any()

提交回复
热议问题