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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With