All six methods return a single value of the sequence type, and can be called with or without a predicate.
Depending on the number of elements that match the predicate
or, if no predicate
is supplied, the number of elements in the source sequence, they behave as follows:
predicate
.InvalidOperationException
is thrown with the message: “Sequence contains no elements”.predicate
, an InvalidOperationException
is thrown with the message “Sequence contains no matching element”.Example
// Returns "a":
new[] { "a" }.First();
// Returns "a":
new[] { "a", "b" }.First();
// Returns "b":
new[] { "a", "b" }.First(x => x.Equals("b"));
// Returns "ba":
new[] { "ba", "be" }.First(x => x.Contains("b"));
// Throws InvalidOperationException:
new[] { "ca", "ce" }.First(x => x.Contains("b"));
// Throws InvalidOperationException:
new string[0].First();
predicate
.predicate
, returns the default value of the sequence type using [default(T)](<http://stackoverflow.com/documentation/c%23/26/keywords/109/default#t=201702071640321629621>)
.Example
// Returns "a":
new[] { "a" }.FirstOrDefault();
// Returns "a":
new[] { "a", "b" }.FirstOrDefault();
// Returns "b":
new[] { "a", "b" }.FirstOrDefault(x => x.Equals("b"));
// Returns "ba":
new[] { "ba", "be" }.FirstOrDefault(x => x.Contains("b"));
// Returns null:
new[] { "ca", "ce" }.FirstOrDefault(x => x.Contains("b"));
// Returns null:
new string[0].FirstOrDefault();
predicate
.InvalidOperationException
is thrown with the message “Sequence contains no elements.”predicate
, an InvalidOperationException
is thrown with the message “Sequence contains no matching element”.Example