Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable repeats function

Tags:

c#

linq

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?

like image 634
M.kazem Akhgary Avatar asked Oct 04 '15 17:10

M.kazem Akhgary


1 Answers

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.

like image 120
Jeroen Vannevel Avatar answered Nov 15 '22 18:11

Jeroen Vannevel