The difference between First,firstordefault,single,singleordefault

Source: Internet
Author: User

Operator

If the source sequence is empty

The source sequence consists of only one element

The source sequence contains multiple elements

First

Throw exception

Returns the element

Returns the first element

FirstOrDefault

Return to Default (TSource)

Returns the element

Returns the first element

Last

Throw exception

Returns the element

Returns the last element

LastOrDefault

Return to Default (TSource)

Returns the element

Returns the last element

Single

Throw exception

Returns the element

Throw exception

Singleordefault

Return to Default (TSource)

Returns the element

Throw exception

Obviously, if the input sequence has only one element, the execution results of these operators are very consistent:) Similarly, if the input sequence is empty, then the operator without "Ordefault" throws an exception (InvalidOperationException) with "Ordefault" operator returns the default value of the element type (the default value for the reference type is Null,int, 0, and so on).

If the input sequence (possibly filtered) contains multiple elements, the results of the execution of these operators differ greatly, and the result of first and last is the name, and single throws an exception. It is important to note that Singleordefault also throws an exception because it does not look like this: if the input sequence has only one element, the element is returned, otherwise the default value is returned. If you need an operator that can handle a multi-element sequence, use first or last. If you need to deal with sequences that may be empty, use FirstOrDefault or LastOrDefault. Note that if you use an operator with "Ordefault", then an empty sequence and a sequence with only the default values will perform exactly the same.

The difference between First,firstordefault,single,singleordefault

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.