Checking if no elements in IEnumerable(Of T) - Linq element and quantifier operators
-
06-09-2019 - |
Question
For my function
IEnumerable<CallbackListRecord> LoadOpenListToProcess(CallbackSearchParams usp);
This line errors when the sequence contains no elements (as it should)
CallbackListRecord nextRecord = CallbackSearch.LoadOpenListToProcess(p).First();
I have changed it to the following
CallbackListRecord nextRecord = null;
IEnumerable<CallbackListRecord> nextRecords = CallbackSearch.LoadOpenListToProcess(p);
if (nextRecords.Any())
{
nextRecord = nextRecords.First();
}
Are there better, easier or more elegant ways to determine if the IEnumerable sequence has no elements?
Solution
You should try to avoid enumerating it more times than necessary (even if short-circuited, like First
and Any
) - how about:
var nextRecord = CallbackSearch.LoadOpenListToProcess(p).FirstOrDefault();
if(nextRecord != null) {
// process it...
}
This works well with classes (since you can just compare the reference to null).
OTHER TIPS
You can shorten the code to the following
var nextrecord = CallbackSearch.LoadOpenListToProcess(p).FirstOrDefault();
nextrecord will either contain the First element if there was one or null if the collection was empty.
If you are anticipating that there could be null values in the sequence, you could handle the enumerator yourself.
var enumerator = CallbackSearch.LoadOpenListToProcess(p).GetEnumerator();
if (enumerator.MoveNext()) {
var item = enumerator.Current;
...
}
You could add an extension method like this:
public static class Extensions
{
public static bool HasElements<T>(this IEnumerable<T> collection)
{
foreach (T t in collection)
return true;
return false;
}
}