TakeLast not working as expected in .net core 3.1

636 Views Asked by At

I have written the below code in the .net core 3.1 console application. It's not working as expected.

var arr = new List<int>(Enumerable.Range(1, 10));
var last5 = arr.TakeLast(5);
foreach (var i in last5)
    Console.WriteLine(i); //writing 6 7 8 9 10
arr.AddRange(new[] { 11, 12, 13, 14, 15 });
foreach (var i in last5)
    Console.WriteLine(i); //writing 6 7 8 9 10 11

It is working as expected (6 7 8 9 10 11 12 13 14 15) If I target the project to in .net core 2.2.

I have used for loop for time being to solve the issue.

Why is it giving different values in .net core 2.2 and 3.1?

1

There are 1 best solutions below

1
On BEST ANSWER

A few observations here:

  1. Calling ToList() after initial call to TakeLast(5) fixes the issue.
  2. Calling arr.TakeLast(5) after arr.AddRange also fixes the issue.

I assume it's a bug that is related to the returned iterator by TakeLast.

In one case(version 2.2), the iterator position is not resetting after the call for the AddRange method. In another(3.1), it's resetting the array start.

Very strange behavior, xD.