Problem with random sort order using Linq-to-Entities

Developers who were talking to me in the past few weeks should have mentioned, that I’m impressed by a technique called LINQ (Language INtegrated Query). This is a feature of .NET and provides the possibility to use SQL like statement in your „normal“ source code. This is very useful, because it enabled the developer to drive powerful selections on data which is in-memory or in other words objects. LINQ comes with a generic interface called IQueryable, which supports all necessary functions for selecting, ordering, querying, etc.

There is a question often asked when using LINQ: Is there a way to perform a LINQ query and having returned the result in a random order? Well, the good news is: There is a way. Using the „orderby“ keyword and e.g. the NewGuid()-Method you are able to create a randomly sorted result.

var result = (from obj in objList orderby Guid.NewGuid() select obj);

This is very easy to understand, if you already know LINQ. But there is an issue, I cannot explain.

I’m doing such a query and the result was… a bit suprising. Of course, the result set was randomly ordered, but there were duplicate entries. The result object count is exactly the same, that means, some entries of the previous object list must be missing.

I proved that while debugging:

Name: „Girls Clothing“
Name: „Girls Clothing“

There is exactly the same object at position 1 and 4 on the result object. I don’t know, why that is happening, so if YOU know that, please leave me a message or comment.

It is important to know that to prevent unexpected results…

GD Star Rating
Problem with random sort order using Linq-to-Entities, 3.0 out of 5 based on 1 rating

Ähnliche Einträge:

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *


Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>