Avi
Avi

Reputation: 16176

Checking if a typed object array is not empty

I have a Item[] _items array of items, where some of the items may be null. I wish to check if the array contains at least one non-null item.

My current implementations seems a little complicated:

    internal bool IsEmtpy { get { return (!(this.NotEmpty)); } }
    private bool IsNotEmpty { get { return ( this.Items.Any(t => t != null));} }

So my question is: Is there a simpler way to check if a typed array of reference objects contains at least one non null object?

Upvotes: 0

Views: 398

Answers (1)

penartur
penartur

Reputation: 9912

There is no complexity in your implementation. Basically, the only way to check whether there are non-null values in the array is to look through all values until you will reach non-null value or the end of the array.

The following code is easier to understand though:

internal bool IsEmtpy { get { return this.Items.All(t => t == null); } }
private bool IsNotEmpty { get { return this.Items.Any(t => t != null); } }

And it is probably better to extend IEnumerable as follows:

public static class Extensions {

    public static bool ContainsOnlyEmpty<TSource>(this IEnumerable<TSource> source) {
        return source.All(t => t == null);
    }

    public static bool ContainsNonEmpty<TSource>(this IEnumerable<TSource> source) {
        return source.Any(t => t != null);
    }

}

and use it like this: bool nonEmpty = this.Items.ContainsNonEmpty();

Upvotes: 2

Related Questions