From 7199578cca80a8a12b8f673134e04131e0efaa4d Mon Sep 17 00:00:00 2001 From: Scott Bilas Date: Mon, 18 Mar 2024 11:28:58 +0100 Subject: [PATCH] TryLast and variants --- src/Core/EnumerableExtensions.cs | 55 ++++++++++++++++++++++++++++++ src/Core/EnumerableExtensions.t.cs | 24 +++++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/Core/EnumerableExtensions.cs b/src/Core/EnumerableExtensions.cs index 076fbf0..114c858 100644 --- a/src/Core/EnumerableExtensions.cs +++ b/src/Core/EnumerableExtensions.cs @@ -81,6 +81,61 @@ public static bool TryFirst(this IEnumerable @this, Func predicat return false; } + public static bool TryFirst(this IReadOnlyList @this, out T? found) + { + if (@this.Count != 0) + { + found = @this[0]; + return true; + } + + found = default; + return false; + } + + public static bool TryLast(this IEnumerable @this, out T? found) + { + var matched = false; + found = default; + + foreach (var element in @this) + { + matched = true; + found = element; + } + + return matched; + } + + public static bool TryLast(this IEnumerable @this, Func predicate, out T? found) + { + var matched = false; + found = default; + + foreach (var element in @this) + { + if (predicate(element)) + { + matched = true; + found = element; + } + } + + return matched; + } + + public static bool TryLast(this IReadOnlyList @this, out T? found) + { + if (@this.Count != 0) + { + found = @this[^1]; + return true; + } + + found = default; + return false; + } + // filtering and searching public static IEnumerable WhereNotNull(this IEnumerable @this) where T: class => diff --git a/src/Core/EnumerableExtensions.t.cs b/src/Core/EnumerableExtensions.t.cs index 013bd06..82156c7 100644 --- a/src/Core/EnumerableExtensions.t.cs +++ b/src/Core/EnumerableExtensions.t.cs @@ -93,6 +93,30 @@ public void TryFirst_WithMatch_ReturnsTrueFound() result2.ShouldBe("b"); } + [Test] + public void TryLast_WithNoMatch_ReturnsFalseDefault() + { + Array.Empty().TryLast(out var result1).ShouldBeFalse(); + result1.ShouldBe(default); + + Array.Empty().TryLast(_ => false, out var result2).ShouldBeFalse(); + result2.ShouldBe(default); + new[] { "a", "b" }.TryLast(_ => false, out var result3).ShouldBeFalse(); + result3.ShouldBe(default); + } + + [Test] + public void TryLast_WithMatch_ReturnsTrueFound() + { + var arr = new[] { "b", "a" }; + + arr.TryLast(out var result1).ShouldBeTrue(); + result1.ShouldBe("a"); + + arr.TryLast(s => s[0] > 'a', out var result2).ShouldBeTrue(); + result2.ShouldBe("b"); + } + [Test] public void WhereNotNull_WithItemsWithNulls_ReturnsFilteredForNull() {