Is there a more efficent way to randomise a set of linq results?
Posted
by
Matthew De'Loughry
on Stack Overflow
See other posts from Stack Overflow
or by Matthew De'Loughry
Published on 2011-01-08T10:20:08Z
Indexed on
2011/01/08
10:54 UTC
Read the original article
Hit count: 252
Hi just wondering if you could help I've produced a function to get back a random set of submission depnding on the amount passed to it, but I worry that even though it works now with a small amount of data when the a large amount is passed through it would become efficent and cause problems.
Just wondering if you could suggest a more efficent way of doing the following:
public List<Submission> GetRandomWinners(int id)
{
List<Submission> submissions = new List<Submission>();
int amount = (DbContext().Competitions
.Where(s => s.CompetitionId == id).FirstOrDefault()).NumberWinners;
for(int i = 1 ; i <= amount; i++)
{
bool added = false;
while (!added)
{
bool found = false;
var randSubmissions = DbContext().Submissions
.Where(s => s.CompetitionId == id && s.CorrectAnswer).ToList();
int count = randSubmissions.Count();
int index = new Random().Next(count);
foreach (var sub in submissions )
{
if (sub == randSubmissions.Skip(index).FirstOrDefault())
found = true;
}
if (!found)
{
submissions.Add(randSubmissions.Skip(index).FirstOrDefault());
added = true;
}
}
}
return submissions;
}
As I say I have this fully working and bringing back the wanted result just I'm not liking the foreach and while checks in there and my head has just turned to mush now try to come up with the above soloution.
Thanks Matt
© Stack Overflow or respective owner