Thursday, December 16, 2010

Randomize with LINQ

Once my colleague showed me a nice way to randomize table records:

I tried to use this trick with LINQ:

but unfortunately it doesn't work. The cities weren't randomized at all. It turned out what during SQL query generation Guid.NewGuid() was treated as a constant and was ignored as the same for all records.

So the right way in this case is to call AsEnumerable() first:

Another interesting thing is what enumerating ci now gives different results every time, so this code might give wrong result:

other might contain first element anyway because records are randomized during second use of ci variable. To avoid this side effect we need to "freeze" elements with ToList():

After that the result will be as expected.

No comments:

Post a Comment