coveo::linq
Implementation of .NET-like LINQ operators in C++
Functions

Returns the only element in a sequence, or a default value. More...

Functions

template<typename = void>
auto coveo::linq::single_or_default () -> detail::single_or_default_impl_0<>
 Returns only element in sequence, or default value. More...
 
template<typename Pred >
auto coveo::linq::single_or_default (const Pred &pred) -> detail::single_or_default_impl_1< Pred >
 Returns only element in sequence satisfying predicate, or default value. More...
 

Detailed Description

The single_or_default operator returns the only element in a sequence, or the only element to satisfy a predicate. If the sequence does not have such an element or has more than one of them, a default value is returned instead.

This is a terminal operator.

.NET equivalent: SingleOrDefault

Function Documentation

◆ single_or_default() [1/2]

template<typename = void>
auto coveo::linq::single_or_default ( ) -> detail::single_or_default_impl_0<>

Returns the only element in a sequence. If the sequence does not have elements or has more than one element, a default-initialized value is returned instead.

Use like this:

const std::vector<int> YES = { 42 };
const std::vector<int> NAY1;
const std::vector<int> NAY2 = { 42, 23, 66 };
using namespace coveo::linq;
auto val1 = from(YES)
auto val2 = from(NAY1)
auto val3 = from(NAY2)
// val1 == 42
// val2 == 0
// val3 == 0
Returns
(Once applied) Only element in sequence, or default value if sequence does not have elements or if it has more than one element.

◆ single_or_default() [2/2]

template<typename Pred >
auto coveo::linq::single_or_default ( const Pred &  pred) -> detail::single_or_default_impl_1<Pred>

Returns the only element in a sequence that satisfy the given predicate. If no element in the sequence or if more than one element in the sequence satisfy the predicate, a default-initialized value is returned instead.

Use like this:

const std::vector<int> YES = { 42, 23, 66 };
const std::vector<int> NAY1 = { 67, 11, 7 };
const std::vector<int> NAY2 = { 42, 24, 66 };
auto is_odd = [](int i) { return i % 2 != 0; };
using namespace coveo::linq;
auto val1 = from(YES)
| single_or_default(is_odd);
auto val2 = from(NAY1)
| single_or_default(is_odd);
auto val3 = from(NAY2)
| single_or_default(is_odd);
// val1 == 23
// val2 == 0
// val3 == 0
Parameters
predPredicate to satisfy.
Returns
(Once applied) Only element in sequence for which pred returned true, or a default value if either no element satisfy pred or more than one element satisfy pred.