Commit a9bd4b6d authored by Anton Bukov's avatar Anton Bukov

Add optional defaultValue argument for firstOrDefault and lastOrDefault

parent 1d09dc8b
...@@ -540,22 +540,22 @@ namespace boolinq { ...@@ -540,22 +540,22 @@ namespace boolinq {
return Linq<S, T>(*this).next(); return Linq<S, T>(*this).next();
} }
T firstOrDefault(std::function<bool(T)> predicate) const T firstOrDefault(std::function<bool(T)> predicate, T defaultValue = T()) const
{ {
try { try {
return where(predicate).next(); return where(predicate).next();
} }
catch (LinqEndException &) {} catch (LinqEndException &) {}
return T(); return defaultValue;
} }
T firstOrDefault() const T firstOrDefault(T defaultValue = T()) const
{ {
try { try {
return Linq<S, T>(*this).next(); return Linq<S, T>(*this).next();
} }
catch (LinqEndException &) {} catch (LinqEndException &) {}
return T(); return defaultValue;
} }
T last(std::function<bool(T)> predicate) const T last(std::function<bool(T)> predicate) const
...@@ -578,18 +578,18 @@ namespace boolinq { ...@@ -578,18 +578,18 @@ namespace boolinq {
return last([](T /*value*/) { return true; }); return last([](T /*value*/) { return true; });
} }
T lastOrDefault(std::function<bool(T)> predicate) const T lastOrDefault(std::function<bool(T)> predicate, T defaultValue = T()) const
{ {
T res = T(); T res = defaultValue;
where(predicate).for_each([&res](T value) { where(predicate).for_each([&res](T value) {
res = value; res = value;
}); });
return res; return res;
} }
T lastOrDefault() const T lastOrDefault(T defaultValue = T()) const
{ {
return lastOrDefault([](T /*value*/) { return true; }); return lastOrDefault([](T /*value*/) { return true; }, defaultValue);
} }
// Export to containers // Export to containers
......
...@@ -37,3 +37,11 @@ TEST(First, NoneElements) ...@@ -37,3 +37,11 @@ TEST(First, NoneElements)
EXPECT_EQ(0, from(src).firstOrDefault()); EXPECT_EQ(0, from(src).firstOrDefault());
EXPECT_EQ(0, from(src).firstOrDefault([](int a){return a%2 == 0;})); EXPECT_EQ(0, from(src).firstOrDefault([](int a){return a%2 == 0;}));
} }
TEST(First, NoneElementsWithArg)
{
std::vector<int> src = {};
EXPECT_EQ(2, from(src).firstOrDefault(2));
EXPECT_EQ(3, from(src).firstOrDefault([](int a){return a%2 == 0;}, 3));
}
...@@ -37,3 +37,10 @@ TEST(Last, NoneElements) ...@@ -37,3 +37,10 @@ TEST(Last, NoneElements)
EXPECT_EQ(0, from(src).lastOrDefault()); EXPECT_EQ(0, from(src).lastOrDefault());
EXPECT_EQ(0, from(src).lastOrDefault([](int a){return a%2 == 0;})); EXPECT_EQ(0, from(src).lastOrDefault([](int a){return a%2 == 0;}));
} }
TEST(Last, NoneElementsWithArgument) {
std::vector<int> src = {};
EXPECT_EQ(2, from(src).lastOrDefault(2));
EXPECT_EQ(3, from(src).lastOrDefault([](int a) { return a % 2 == 0; }, 3));
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment