While execution of following linq, I get this exception:
" Sequence contains no elements"
Linq code:
newGradeRow[rowCnt + 1 + "Grade " + ExamName] =
objDataSet.Tables[1].Rows.Cast<DataRow>()
.Where(p => Convert.ToDecimal(p["EMG_MARKS_ABOVE"]) <= extSubMarks
&& extSubMarks <= Convert.ToDecimal(p["EMG_MARKS_BELOW"]))
.Select(p => Convert.ToString(p["EMG_GRADE_NAME"]))
.First();
Can any one help me on this?
SingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
FirstOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the first element of a sequence, or a specified default value if the sequence contains no elements. FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.
The exception is thrown in the First
method call if the sequence is empty as it is stated in the documentation. In this case it is better to use the FirstOrDefault method - it will return the default value (in specific case null
) and no exception will be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With