-
-
Notifications
You must be signed in to change notification settings - Fork 13
IEnumerable.single() method
Marcel Kloubert edited this page Sep 25, 2015
·
3 revisions
Returns the one and only element of the sequence (s. Single()).
An exception is thrown, if more than one element was found or no element was found.
public function single([ predciate $predicate = null ]]) : mixed;
Name | Type | Description |
---|---|---|
$predicate | [[predicate | Predicate]] |
The custom predciate to use.
The one and only value of the sequence.
use \System\Collections\ElementNotFoundException;
use \System\Collections\EnumerableException;
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(11);
$seq2 = Enumerable::fromValues();
$seq3 = Enumerable::fromValues(1, 2);
// 11
$val1 = $seq1->single();
try {
$val2 = $seq2->single();
}
catch (ElementNotFoundException $ex) {
// code goes here
}
try {
$val3 = $seq3->single();
}
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\ElementNotFoundException;
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';
try {
$val1 = $seq1->single($predicate);
}
catch (ElementNotFoundException $ex) {
// code goes here
}
// 10
$val2 = $seq2->single($predicate);
try {
$val3 = $seq3->single($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\ElementNotFoundException;
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;
};
try {
$val1 = $seq1->single($predicate);
}
catch (ElementNotFoundException $ex) {
// code goes here
}
// 10
$val2 = $seq2->single($predicate);
try {
$val3 = $seq3->single($predicate);
}
catch (EnumerableException $ex) {
// the code should be go here
$thrownEx = $ex;
}
// (true)
$is1 = isset($thrownEx) &&
($thrownEx instanceof EnumerableException);
// (false)
$is2 = isset($val3);