1

I'am trying to return random entities from i join query that i wrote. But it does not return randomly. Entities always come as same before. What can be the problem ? Here is the query

 var query = (from b in db.BrandTbls.AsQueryable() join m in db.ShoeModelTbls on b.BrandID equals m.BrandID join s in db.ShoeTbls on m.ModelID equals s.ModelID join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g orderby Guid.NewGuid() select new {g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price,g.Key.PrimaryColor,g.Key.SecondaryColor}).OrderBy(x => Guid.NewGuid()).Take(8); 
4
  • orderby Guid.NewGuid() would be similar to orderby 1. It won't cause random returns. Commented May 27, 2014 at 19:16
  • I saw this way from some documents that i found internet. Commented May 27, 2014 at 19:17
  • 1
    @Tartar Not everything you see on the internet is correct. Commented May 27, 2014 at 19:37
  • Ofcourse not, but i saw this solution atleast 3 different web pages then i tought it was correct. Commented May 27, 2014 at 19:39

2 Answers 2

2

GUIDs are not random numbers. They are unique numbers. There are a number of ways of generating unique values, many of which are not random at all. It is even possible for generated GUID values to be monotone increasing, which would mean that sorting on new guids for each item in the sequence would result in every item staying in exactly the same ordering.

Shuffling a set of data is a well defined problem, with well defined solutions. You should use one of the well documented solutions to the problem of shuffling to reliably and efficiently shuffle a collection of data.

Sign up to request clarification or add additional context in comments.

Comments

1

orderby Guid.NewGuid() would be similar to orderby 1. It won't cause random returns.

I'd suggest letting SQL do the randomization act. Look at this for an example:

Random row from Linq to Sql

You can create an empty Random method that LINQ will translate into a Random T_SQL call to SQL.

1 Comment

But orderby Guid.NewGuid() does work with EF4+. See stackoverflow.com/a/4651405/158074

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.