views:

458

answers:

3

For my function

public static 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?

+4  A: 

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).

Marc Gravell
Works fine, thanks.
CRice
Any specific reason to use the var keyword in this case?
CRice
@boon - well, it's shorter... No, using var is always equivalent to the type the compiler resolves var to be (CallbackListRecord in this case).
Jonathan
@boon - one very simple reason; without it the text scrolled off the page ;-p
Marc Gravell
+1  A: 

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.

JaredPar
A: 

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;
  ...
}
YotaXP