-
-
Notifications
You must be signed in to change notification settings - Fork 13
IEnumerable.singleOrDefault() method
Marcel Kloubert edited this page Sep 30, 2015
·
6 revisions
Returns the one and only element of the sequence, or a default value if no element was found (s. SingleOrDefault()).
An exception is thrown, if more than one element was found.
public function singleOrDefault([mixed $predicateOrDefaultValue = null
[, mixed $defValue = null ]]) : mixed;
Name | Type | Description |
---|---|---|
$predicateOrDefaultValue | [[predicate | Predicate]]|mixed |
$defValue | mixed | [OPTIONAL] The value to return if sequence is empty. DEFAULT value is NULL . |
The predicate or default value.
If it is a callable, the predicate has the following structure:
function (mixed $item, IIndexedItemContext $ctx) : bool;
The value to return if sequence is empty.
The one and only value of the sequence or the default value.
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues();
$seq3 = Enumerable::fromValues(1, 2);
// 11
$val1 = $seq1->singleOrDefault();
// (null)
$val2 = $seq2->singleOrDefault();
try {
$val3 = $seq3->singleOrDefault();
}
catch (EnumerableException $ex) {
// the code should be go here
$thrownEx = $ex;
}
// (true)
$is1 = isset($thrownEx) &&
($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues();
// 11
$val1 = $seq1->singleOrDefault(false);
// (false)
$val2 = $seq2->singleOrDefault(false);
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues(10, 11);
$seq3 = Enumerable::fromValues(9, 10, 11);
$predicate = '$x => $x < 11';
// (null)
$val1 = $seq1->singleOrDefault($predicate);
// 10
$val2 = $seq2->singleOrDefault($predicate);
try {
$val3 = $seq3->singleOrDefault($predicate);
}
catch (EnumerableException $ex) {
// the code should be go here
$thrownEx = $ex;
}
// (true)
$is1 = isset($thrownEx) &&
($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues(10, 11);
$seq3 = Enumerable::fromValues(9, 10, 11);
$predicate = function ($x) {
return $x < 11;
};
// (null)
$val1 = $seq1->singleOrDefault($predicate);
// 10
$val2 = $seq2->singleOrDefault($predicate);
try {
$val3 = $seq3->singleOrDefault($predicate);
}
catch (EnumerableException $ex) {
// the code should be go here
$thrownEx = $ex;
}
// (true)
$is1 = isset($thrownEx) &&
($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);