Skip to content

Instantly share code, notes, and snippets.

@TheAngryByrd
Last active August 7, 2025 15:49
Show Gist options
  • Save TheAngryByrd/8b7d02f8835482e17fd53230fea1fa9e to your computer and use it in GitHub Desktop.
Save TheAngryByrd/8b7d02f8835482e17fd53230fea1fa9e to your computer and use it in GitHub Desktop.
F# TryGetNonEnumeratedCount helper
module Seq =
open System.Linq
/// Attempts to determine the number of elements in a sequence without forcing an enumeration.
let inline tryLength (xs : seq<_>) =
match Enumerable.TryGetNonEnumeratedCount xs with
| true, count -> ValueSome count
| _ ->
match xs with
// F# list implements IReadOnlyCollection/IReadOnlyList
// but TryGetNonEnumeratedCount doesn't support it
// see https://github.com/dotnet/runtime/issues/42254
| :? List<_> as l -> ValueSome (List.length l)
| _ -> ValueNone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment