Skip to content

Commit

Permalink
TryLast and variants
Browse files Browse the repository at this point in the history
  • Loading branch information
scottbilas committed Mar 18, 2024
1 parent 531a95c commit 7199578
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/Core/EnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,61 @@ public static bool TryFirst<T>(this IEnumerable<T> @this, Func<T, bool> predicat
return false;
}

public static bool TryFirst<T>(this IReadOnlyList<T> @this, out T? found)
{
if (@this.Count != 0)
{
found = @this[0];
return true;
}

found = default;
return false;
}

public static bool TryLast<T>(this IEnumerable<T> @this, out T? found)
{
var matched = false;
found = default;

foreach (var element in @this)
{
matched = true;
found = element;
}

return matched;
}

public static bool TryLast<T>(this IEnumerable<T> @this, Func<T, bool> 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<T>(this IReadOnlyList<T> @this, out T? found)
{
if (@this.Count != 0)
{
found = @this[^1];
return true;
}

found = default;
return false;
}

// filtering and searching

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> @this) where T: class =>
Expand Down
24 changes: 24 additions & 0 deletions src/Core/EnumerableExtensions.t.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,30 @@ public void TryFirst_WithMatch_ReturnsTrueFound()
result2.ShouldBe("b");
}

[Test]
public void TryLast_WithNoMatch_ReturnsFalseDefault()
{
Array.Empty<string>().TryLast(out var result1).ShouldBeFalse();
result1.ShouldBe(default);

Array.Empty<string>().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()
{
Expand Down

0 comments on commit 7199578

Please sign in to comment.