mercredi 10 juin 2015

how to get random rows in linq with last inserted rows on top

i am trying to show random products in view for each request, this OrderBy(r => Guid.NewGuid()) works fine, but i am trying to increase perfomance when table records are huge , so i used second option from here

my action:

public ActionResult ProductType(string id)
{
List<ProductsView> productlist = (from a in this.dbo.ProductTable
                                 join ca in dbo.Category on a.CategoryID equals ca.CategoryID
                                 where ca.Category == id 
                                 select new ProductsView()
                                 {
                                 CategoryID = c.CategoryID,
                                 Categorycount = c.Categorycount
                                 }).ToList<ProductsView>();

// here shuffle or mix products

int count = productlist.Count();
int index = new Random().Next(count);
ViewBag.Products = productlist.Skip(index).ToList();

 return View();

}

but when view returns some records are missing, eg:

first request count 4 index 1

shows 3 product in view

second request count 4 index 2

shows 2 product in view

third request count 4 index 3

shows 1 product in view

finally i have one more requirement can i show last inserted rows in top and let other products be random ?

may i know what i am missing ?

any help would be great.




Aucun commentaire:

Enregistrer un commentaire