0

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?

8
  • 2
    Why do you think this is complicated? Commented Jul 2, 2012 at 8:47
  • 2
    Why do you think it's complicated? it seems quite clear and compact to my eyes. Maybe you can put this logic to a custom extension mehod, but the logic itself won't change. Commented Jul 2, 2012 at 8:47
  • 1
    Don't agree with the downvote, it's a clear question. Commented Jul 2, 2012 at 8:50
  • @leppie (and Steve B) I hate the double negation. In my implementation it's empty if it's not not empty :( Commented Jul 2, 2012 at 8:58
  • @AdamHouldsworth Thanks. Downvotes are so unhelpful, and are the reason why I quit "programmers"... Commented Jul 2, 2012 at 8:58

1 Answer 1

2

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();

Sign up to request clarification or add additional context in comments.

9 Comments

@leppie Please, forgive me my terrible English :)
No problem, I had to look up the meaning too ;p
@leppie I didn't remember the word exactly, so I even opened the dictionary to look up for it... but then I completely forgot about it and submitted the answer :)
Thanks - It's the "all" I've been missing, though now that I understand the answer I think the double negation is more efficient because most of my arrays are "mostly full" so the any-not-null will return faster.
@Avi - no, there's no performance difference. Both Any and All return as soon as a non-null element is found.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.