Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Any() vs MoveNext()

Tags:

c#

linq

Using Linq on collections, which one is best for finding that collection is not empty?

HasChild = Childs.GetEnumerator().MoveNext() ? true : false;

and

HasChild = Childs.Any() ? true : false;
like image 475
VIJI Avatar asked Sep 26 '16 11:09

VIJI


1 Answers

Since IEnumerator<T> implements IDisposable (and thus can allocate resources) you have to put (in general case) not a simple line

// Don't do this: it can cause a resource leakage
HasChild = Childs.GetEnumerator().MoveNext() ? true : false;

but a fragment

bool HasChild = false;

using (var en = Childs.GetEnumerator()) {
  HasChild = en.MoveNext(); // You have no need in ternary operator here
}

And it seems too wordy when in case of Any all you should do

bool HasChild = Childs.Any();

And Enumerable<T>.Any will do the wordy part for you:

http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0

    public static bool Any<TSource>(this IEnumerable<TSource> source) {
        if (source == null) throw Error.ArgumentNull("source");
        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            if (e.MoveNext()) return true;
        }
        return false;
    }
like image 183
Dmitry Bychenko Avatar answered Sep 28 '22 02:09

Dmitry Bychenko