I have recently found the following lines in a for loop are giving me an error. The error is from the stepEndTime, the last line of code shown below:
EnumerableRowCollection<DERP_Dataset.tblActualValueFloatRow> RowFirstStep = DERP_DataServiceDataSet.tblActualValueFloat.Where(t => t.PointSliceID == StepPointSliceId && t.ActualValue == stepnumbers[stepIndex] && t.UTCDateTime >= startDate).OrderBy(o => o.UTCDateTime);
EnumerableRowCollection<DERP_Dataset.tblActualValueFloatRow> RowNextStep = DERP_DataServiceDataSet.tblActualValueFloat.Where(t => t.PointSliceID == StepPointSliceId && t.ActualValue > stepnumbers[stepIndex] && t.UTCDateTime >= startDate).OrderBy(o => o.UTCDateTime);
DateTime StepStartTime = (RowFirstStep.First().HasErrors) ? DateTime.MaxValue : RowFirstStep.First().UTCDateTime;
string rowNextStepUTCDateTimeString = RowNextStep.First().UTCDateTime.ToString();
DateTime StepEndTime = (RowNextStep.First().HasErrors) ? DateTime.MaxValue : RowNextStep.First().UTCDateTime;
Error:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Message: {"Sequence contains no elements"}
Source: System.Core
StackTrace: at System.Ling.Enumerable.First[TSource](IEnumerable'1 source)
Attempts to figure this out:
- Link found here.
- Using RowNextStep.First().isNull is not a Boolean, so can't use in the loop?
- Tried putting in a dummy string variable, but got exact same error and exception, so didn't learn anything new when trying to debug.
- I believe RowNextStep.First().HasErrors is evaluating to false each time, including when I encounter the error. Not certain 100%.
Any illumination on this matter would be greatly appreciated.
Edit
Modified the code with suggestions, and it produced a much more useful error.
DateTime StepEndTime = (RowNextStep.FirstOrDefault().HasErrors) ? DateTime.MaxValue : RowNextStep.First().UTCDateTime;
Error is definitely null. As I now get:
A first chance exception of type 'System.NullReferenceException'
Is there any way to check for null besides !RowNextStep.First().Any? I will use it if I must, but I like to avoid negations if possible.