Reputation: 77
i want to retrieve 15 records from a table of around 50 records. but i want all records to be generated randomly. if i take a random number and write something like:
var result = (from r in sc.Subjects
where (r.SubName == sub && r.Level == lev)
select r).skip(randomnumber).take(10),
the starting record will be random but the next 9 will be in sequence. so any idea on how i can have all 10 records random using linq to sql?
Upvotes: 3
Views: 6495
Reputation: 15242
It would probably be better to do this with a for
loop to get the item then using LINQ
var result = new List<subject>();
for(i = 0; i < 10; i++)
{
randomnumber = GenerateNewRandomNumber();
result.Add(sc.Subjects.Where(r => r.SubName == sub && r.Level == lev).Skip(randomnumber).take(1).First;
}
Upvotes: 0
Reputation: 41757
Try the following:
private static Random Generator = new Random();
...
var result = sc.Subjects.Where(s => s.SubName == sub && s.Level == lev).OrderBy(s => Generator.Next()).Take(10);
Upvotes: 0
Reputation: 46859
I use this in one of my sites, to show random ads from a table. Its EF4.0, but the Linq2SQL is probably the same or similar:
myAds = (from q in db.Ads select q).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
Upvotes: 8