IsNullOrEmpty equivalent for Array? C#

后端 未结 11 1431
轻奢々
轻奢々 2020-12-08 18:42

Is there a function in the .NET library that will return true or false as to whether an array is null or empty? (Similar to string.IsNullOrEmpty).

I had

相关标签:
11条回答
  • 2020-12-08 19:21
    if (array?.Any() != true) { ... }
    
    • Don't forget having using System.Linq;
    • Note one must explicitly compare against true since the underlying type is bool?
    0 讨论(0)
  • 2020-12-08 19:24

    Checking for null or empty or Length has been simplified with C# Linq. With null coalesce operator, one can simply do this:

    if (array?.Any())
        return true;
    else return false;
    
    0 讨论(0)
  • 2020-12-08 19:27

    You can also use Any on creating your extension method:

    public static bool IsNullOrEmpty<T>(this T[] array) where T : class
        {
            return (array == null || !array.Any());
        }
    

    Don't forget to add using System.Linq; on your using statements.

    0 讨论(0)
  • 2020-12-08 19:29

    This is an updated C# 8 version of the (currently) up-voted answer

    public static bool IsNullOrEmpty<T>([NotNullWhen(false)] this T[]? array) =>
        array == null || array.Length == 0;
    
    0 讨论(0)
  • 2020-12-08 19:34

    In case you initialized you array like

    string[] myEmpytArray = new string[4];
    

    Then to check if your array elements are empty use

    myEmpytArray .All(item => item == null)
    

    Try

     public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
     {
        if (collection == null || collection.Count == 0)
            return true;
        else
           return collection.All(item => item == null);
     }
    
    0 讨论(0)
提交回复
热议问题