Difference between SingleOrDefault and firstorDefault

Forums LINQDifference between SingleOrDefault and firstorDefault
Staff asked 3 years ago

Answers (2)

Add Answer
monika gabani Marked As Accepted
Staff answered 3 years ago

SingleOrDefault:

If you want an exception to be thrown if the result set contains many records, use SingleOrDefault.

It returns the default value for the type when your result set returns 0 records.

It throws an exception if your result set returns many records.

FirstOrDefault:

If you always want 1 record no matter what the result set contains, use FirstOrDefault.

It returns the default value for the type when your result set returns 0 records.

It  returns the first record if your result set returns many records.

 

Staff answered 3 years ago

    -- SingleOrDefault()

  • returns the default value for the type (e.g. default for int is 0)
  • List<int> items = new List<int>() {10,20,30,40,50};
    //Throw the exception after satisfied the condition more than one elements
    int result = items.Where(item => item == 10).SingleOrDefault();

    -- FirstOrDefault()

  • that is returns the default value for the type
    List<int> items = new List<int>() {10,20,30,40,50};
    //Throw the no exception after satisfied the condition more than one elements.
    int result = items.Where(item => item == 10).FirstOrDefault ();

     

Subscribe

Select Categories