I have a LINQ to Entities written, which is making use of the following OrderBy:
.OrderBy(i => Guid.NewGuid())
The above randomises the ordering of the dataset, so each run of this code produces a different ordering, everytime.
However, if I do any of the following, the dataset is NOT randomised and is the exact SAME for all 3 OrderBy, see below:
.OrderBy(i => new Guid("5fd3e5e7-b172-42f5-a4dd-da4212201a31"))
.OrderBy(i => new Guid("beb7345c-1421-48e0-b177-51b2bb065214"))
Guid g = Guid.NewGuid();
.OrderBy(i => g)
You can see the 3 OrderBy above are using different Guids, so why do they produce the same order? Why is it that Guid.NewGuid() randomises the list everytime I run this piece of code, but the other 3 OrderBy statements produce the same result everytime?
My issue is, I need to pass in a value into a function, which is used within the LINQ to Entities dataset to randomise the results depending on the value, however I also need to be able to pass the same value and retrieve the same order of randomness.
Thanks.
This behavior when you have Guid.NewGuid() is by design in Entity Framework, it mimics SQL's ORDER BY NEWID(), to allow random ordering. When you specify a constant Guid, it merely orders by this constant value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With