Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ : exception as " Sequence contains no elements" [closed]

Tags:

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?

like image 638
Sumith Amin Avatar asked Nov 27 '11 12:11

Sumith Amin


People also ask

What is the difference between FirstOrDefault and SingleOrDefault?

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.

What is FirstOrDefault C#?

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.


1 Answers

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.

like image 115
danyloid Avatar answered Sep 29 '22 01:09

danyloid