Skip to content

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

@AnnaVel

Description

@AnnaVel

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions