Random Records

3 posts, 0 answers
  1. Jay
    Jay avatar
    28 posts
    Member since:
    Apr 2006

    Posted 13 Sep 2010 Link to this post

    Is there anyway to completely randomize the result set like sql server's "order by newid()" trick?
  2. Petko_I
    Petko_I avatar
    184 posts

    Posted 15 Sep 2010 Link to this post

    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)

    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.

    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
  3. DevCraft banner
  4. Markus
    Markus avatar
    205 posts
    Member since:
    Nov 2005

    Posted 11 Dec 2013 Link to this post

    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.


    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;

Back to Top