Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Last() throws an exception when applied on a concatenation of a collection with two empty collections #108477

Closed
AnnaVel opened this issue Oct 2, 2024 · 2 comments · Fixed by #108486
Assignees
Labels
area-System.Linq bug in-pr There is an active PR which will close this issue when it is merged regression-from-last-release
Milestone

Comments

@AnnaVel
Copy link

AnnaVel commented Oct 2, 2024

Description

Hi, we've run into an issue with .NET 9, preview 2 onwards. If you have an enumerable with some elements and you concatenate it with other two enumerables which are empty the Last() method, applied to the result concatenation, throws an InvalidOperationException 'Sequence contains no elements'.

Reproduction Steps

IEnumerable<int> results = new List<int>() { 1, 2, 3 }.Concat(new List<int>()).Concat(new List<int>());

bool any = results.Any(); // true
int count = results.Count(); // 3
int last = results.Last(); // 'Sequence contains no elements.'

Same code in a project: https://github.com/AnnaVel/ConcatenatedLast

Expected behavior

Last() should return 3.

Actual behavior

Last() throws an exception.

Regression?

Yes. This does not reproduce in .NET 9 preview 1, but reproduces in .NET 9 preview 2 and later.

Known Workarounds

One could just use collection.ElementAt(collection.Count() - 1).

Configuration

It is not likely this is a configuration-specific problem.

Other information

No response

@dotnet-policy-service dotnet-policy-service bot added the untriaged New issue has not been triaged by the area owner label Oct 2, 2024
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-linq
See info in area-owners.md if you want to be subscribed.

@andrewjsaid
Copy link
Contributor

andrewjsaid commented Oct 2, 2024

The reason for this bug is that in Concat.SpeedOpt we have loop through the tail using this

while ((node = node!.PreviousN) is not null)

while ((node = node!.PreviousN) is not null);

Which is defined as

private ConcatNIterator<TSource>? PreviousN => _tail as ConcatNIterator<TSource>;

private ConcatNIterator<TSource>? PreviousN => _tail as ConcatNIterator<TSource>;

However the "base case" of the tail is a Concat2Iterator``1 so null is returned and so the "base source" isn't inspected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-System.Linq bug in-pr There is an active PR which will close this issue when it is merged regression-from-last-release
Projects
None yet
4 participants