Checking for missing elements in IEnumerable (Of T) - Linq elements and quantifiers

For my function

IEnumerable<CallbackListRecord> LoadOpenListToProcess(CallbackSearchParams usp); 

This error line when the sequence contains no elements (as it should)

 CallbackListRecord nextRecord = CallbackSearch.LoadOpenListToProcess(p).First(); 

I changed it to the following

 CallbackListRecord nextRecord = null; IEnumerable<CallbackListRecord> nextRecords = CallbackSearch.LoadOpenListToProcess(p); if (nextRecords.Any()) { nextRecord = nextRecords.First(); } 

Are there better, simpler, or more elegant ways to determine if an IEnumerable sequence has any elements?

+4
source share
4 answers

You should try to avoid listing it more time than necessary (even if a short circuit such as 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).

+6
source

You can shorten the code to the next

 var nextrecord = CallbackSearch.LoadOpenListToProcess(p).FirstOrDefault(); 

nextrecord will either contain the first element if it was one or null if the collection was empty.

+1
source

If you expect the sequence to have null values, you can process the enumeration yourself.

 var enumerator = CallbackSearch.LoadOpenListToProcess(p).GetEnumerator(); if (enumerator.MoveNext()) { var item = enumerator.Current; ... } 
+1
source

You can add an extension method as follows:

 public static class Extensions { public static bool HasElements<T>(this IEnumerable<T> collection) { foreach (T t in collection) return true; return false; } } 
0
source

All Articles