I have this function:
/// <summary>
/// Returns an array of random articles, ID and titles only
/// </summary>
/// <param name="SectionID">Section ID to return</param>
/// <param name="Count">Number of articles to return</param>
/// <returns></returns>
public ArticleOverview[] RandomArticles(int SectionID, int Count)
{
ArticleOverview[] ReturnLinks;
// Pick a random tutorial and redirect to it
using (MainContext db = new MainContext())
{
// Select rows
var q = (from c in db.tblArticles where c.IsDeleted == false && c.SectionID == SectionID select new { c.ID, c.Title });
int count = q.Count();
int index = new Random().Next(count);
var Articles = q.Skip(index).Take(Count);
// Size array
ReturnLinks = new ArticleOverview[Articles.Count()];
int InsertIx = 0;
foreach (var Rec in Articles)
{
ReturnLinks[InsertIx] = new ArticleOverview(Rec.ID, Rec.Title, SectionID);
InsertIx++;
}
}
return ReturnLinks;
}
There are two problems with this method:
- If it selects one of the last records, it will return less records than intended, IE if recordset count is 100 and we are selecting 10 records and it returns index 95 it will only return 5 records and not 10
- The returned records are ordered, they are not jumbled. The returned records need to be randomised and not ordered as they exist sequentially in the database.
Thanks for any help! I’m using SQL Server Express 2008 R2.
Just use the method in Random row from Linq to Sql to do an
orderby ctx.Random()and do a.Take(sampleSize)on the results instead ofFirstOrDefault