Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if no elements in IEnumerable(Of T) - Linq element and quantifier operators

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?

like image 541
CRice Avatar asked Mar 01 '23 16:03

CRice


1 Answers

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

like image 116
Marc Gravell Avatar answered Apr 06 '23 00:04

Marc Gravell