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…


Sex ist eine Schlacht, Liebe ist Krieg. #dotnet #developer #gamer #bisexual

1 Kommentar

Frederic delaporte · 6. Juli 2015 um 11:02

See this question on SO, the linq order by seems to expect the ranking function to be stable, which is not the case with a random generator.
Linq to entities translate this to a sql query which may get different ranking for the same entity (as soon as your queries use includes or joins). Then it causes the entity to get duplicated in the result list.

Schreibe einen Kommentar

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

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.