From b76bd7b610eba2c7d72468847d1650c399cd60ad Mon Sep 17 00:00:00 2001 From: prozolic <42107886+prozolic@users.noreply.github.com> Date: Sat, 17 Jan 2026 20:28:09 +0900 Subject: [PATCH 1/2] Add early return in TryGetLast for empty results. When source is an Iterator and GetCount(onlyIfCheap: true) returns a valid count (not -1), check if count <= _minIndexInclusive. In this case, immediately return with found=false. --- .../System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs index 944e0fa4cda70e..723bcc5c3f981b 100644 --- a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs +++ b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs @@ -441,8 +441,14 @@ public override Iterator Take(int count) { if (_source is Iterator iterator && iterator.GetCount(onlyIfCheap: true) is int count && - count > _minIndexInclusive) + count != -1) { + if (count <= _minIndexInclusive) + { + found = false; + return default; + } + // If there's no upper bound, or if there are fewer items in the list // than the upper bound allows, just return the last element of the list. // Otherwise, get the element at the upper bound. From 511e2e8a1e7f35b74b2ea1822ea62225f2d219fd Mon Sep 17 00:00:00 2001 From: prozolic <42107886+prozolic@users.noreply.github.com> Date: Sun, 18 Jan 2026 07:25:20 +0900 Subject: [PATCH 2/2] Update src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs Co-authored-by: Stephen Toub --- src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs index 723bcc5c3f981b..0a98b5c88473ca 100644 --- a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs +++ b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs @@ -441,7 +441,7 @@ public override Iterator Take(int count) { if (_source is Iterator iterator && iterator.GetCount(onlyIfCheap: true) is int count && - count != -1) + count >= 0) { if (count <= _minIndexInclusive) {