Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - FirstOrDefault() then Select()

Tags:

c#

linq

I have the following LINQ query that fires and exception when the FirstOrDefault() returns null. Ideally I would like to avoid the null check. Is there a way to do this? I wish to return 0 if there are no CPOffsets that satisfy the FirstOrDefault() call.

double offset = OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime).CPOffset; 

The only way I can see to achieve this is the following:

CPOffset cpOffset = OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime); double offset = cpOffset != null ? cpOffset.CPOffset : 0; 

Is there another more succinct way? Using Select() after the FirstorDefault() doesn't compile but I thought might be appropriate here?

like image 891
Simon Avatar asked Mar 20 '13 23:03

Simon


People also ask

What is the difference between first () and FirstOrDefault () Select methods in Linq?

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data.

What is the use of FirstOrDefault in Linq?

Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection. For that, use the FirstorDefault() method to display the default value.

What is faster than FirstOrDefault?

Code walkthrough I hope now you know that retrieving the data by a DictionaryKey is very very faster than FirstOrDefault() LINQ function. Here we see a very huge difference in execution time to retrieve the data in both ways. One of the data was retrieved by FirstOrDefault() and it has taken ~20.02 ms.

Does FirstOrDefault execute query?

All standard Linq operators, which return single, non-enumerable result, are executed immediately at the point where query is declared. So, FirstOrDefault , Count , Sum and other operators which return single value are executed immediately.


1 Answers

I think this should work, I'm not near by VS to check it out...

OrderedOffsets.Where(o => o.OffsetDateTime > cpTime).Select(x => x.CPOffset).FirstOrDefault(); 
like image 199
NSGaga-mostly-inactive Avatar answered Sep 28 '22 23:09

NSGaga-mostly-inactive