This is a migrated thread and some comments may be shown as answers.

Random Records

2 Answers 64 Views
LINQ (LINQ specific questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Jay
Top achievements
Rank 1
Jay asked on 13 Sep 2010, 10:22 PM
Is there anyway to completely randomize the result set like sql server's "order by newid()" trick?

2 Answers, 1 is accepted

Sort by
0
Petko_I
Telerik team
answered on 15 Sep 2010, 05:09 PM
Hello Jay,

The randomization in a LINQ query cannot be propagated to the database server with OpenAccess. However, if you retrieve the persistent objects in memory, you can benefit from the LINQ to Objects implementation. You can then order your items by a random number generated with the Random class.

using (NorthwindContext context = new NorthwindContext())
{
    Random random = new Random();
    var query = context.Categories;
    var orderedQuery = query.ToList().OrderBy(x => random.Next());
    foreach (var category in orderedQuery)
    {
        Console.WriteLine(category.CategoryName);
    }
}

There is another option which is situationally useful – you can create a view which performs the ordering on the database server side and map it to a persistent type. Each time you retrieve a collection of persistent objects from this view, you will get them in a random order unless you order them explicitly.

I hope this helps. Do not hesitate to contact us if you have more questions.

Regards,
Petko_I
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Markus
Top achievements
Rank 2
answered on 11 Dec 2013, 01:10 PM
I am not sure if this might be related to your questions but I had to get a random number of records from a DB and did it like this.

... .OrderBy(x => Guid.NewGuid()).Take(3);

works like a charm for me.

Markus

public virtual IQueryable<zuol_mobile.T_banner> GetRandomBanners()
       {
 
           var Banners = repository.GetAllBy(p => p.BannerID != 1).OrderBy(x => Guid.NewGuid()).Take(3);
 
           if (Banners == null)
           {
               throw new HttpResponseException(HttpStatusCode.MethodNotAllowed);
           }
 
           return Banners;
       }

Tags
LINQ (LINQ specific questions)
Asked by
Jay
Top achievements
Rank 1
Answers by
Petko_I
Telerik team
Markus
Top achievements
Rank 2
Share this question
or