Skip to content

Commit

Permalink
More helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
scottbilas committed Mar 18, 2024
1 parent 54d900b commit 531a95c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Core/EnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public static T SingleOr<T>(this IEnumerable<T> @this, Func<T> defaultValueGener
return value;
}

public static T First<T>(this IReadOnlyList<T> @this) =>
@this[0];
public static T Last<T>(this IReadOnlyList<T> @this) =>
@this[^1];

public static bool TryFirst<T>(this IEnumerable<T> @this, out T? found)
{
foreach (var element in @this)
Expand Down
29 changes: 29 additions & 0 deletions src/Core/EnumerableExtensions.t.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Collections;

class EnumerableExtensionsTests
{
[Test]
Expand Down Expand Up @@ -40,6 +42,33 @@ public void SingleOr_WithMoreThanOne_Throws()
.Message.ShouldContain("more than one");
}

class DirectIndexTest<T>(int count, int index, T value) : IReadOnlyList<T>
{
public IEnumerator<T> GetEnumerator() => throw new InvalidOperationException();
IEnumerator IEnumerable.GetEnumerator() => throw new InvalidOperationException();

public int Count => count;
public T this[int i] => i == index ? value : throw new InvalidOperationException();
}

[Test]
public void First_WithReadOnlyList_ShouldOnlyCallIndexer()
{
var list = new DirectIndexTest<int>(100, 0, 123);

list.First().ShouldBe(123);
Should.Throw<InvalidOperationException>(() => list.AsEnumerable().First());
}

[Test]
public void Last_WithReadOnlyList_ShouldOnlyCallIndexer()
{
var list = new DirectIndexTest<int>(100, 99, 234);

list.Last().ShouldBe(234);
Should.Throw<InvalidOperationException>(() => list.AsEnumerable().Last());
}

[Test]
public void TryFirst_WithNoMatch_ReturnsFalseDefault()
{
Expand Down

0 comments on commit 531a95c

Please sign in to comment.