M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

IEnumerable repeats function

I have faced a strange problem. Here I reproduced the problem.

Random r = new Random();
List<int> x = new List<int> {1, 2, 3, 4, 5, 6};

var e = x.OrderBy(i => r.Next());
var list1 = e.ToList();
var list2 = e.ToList();

bool b = list1.SequenceEqual(list2);
Console.WriteLine(b); // prints false

Until now, I thought that Linq functions get executed when they are called. But, in this method it seems after I call ToList the Linq function OrderBy executes again. Why is that so?

Upvotes: 13

Views: 436

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

You're looking at deferred execution. When you create a LINQ query it's basically a blueprint that says "when requested, perform these steps to manipulate the datasource". The tricky part here is that this request is only done by a distinct set of LINQ operations (.ToList() is one of these).

So when you call e.ToList() once it will randomize the data source because that's what the blueprint says it has to do. When you then call .ToList() again on this same blueprint, it starts again from the start and randomizes again.

A blueprint doesn't contain any state, it just says what should be done at each step of the way.

Upvotes: 19

Related Questions