While refactoring some C# code I came across some lines that seemed a bit awkward. I was trying to sort a list or an array randomly. That code was written before Linq came into the .Net Framework, so now I was able to figure out a new approach.
Since Linq to Objects has some similarities with SQL, I got the idea of trying the same approach that I used several times in SQL, which was ordering a SELECT statement using ORDER BY RAND().
The result is shown bellow.

It uses the Extension Methods syntax of Linq to save some bytes on the source code ![]()






You can also use Guid.NewGuid() instead of r.Next(), in order to save even more bytes ^^. Further, the traditional SQL approach of using “ORDER BY RAND()” to obtain a random sample isn’t very efficient, since it needs a full table scan, thus slowing the query for tables with many rows (like, say, more than 1000). To speed things up, check this page. MSSQL also has the TABLESAMPLE clause, but there seems to be some caveats around it.
Order by Random… dessa nao me ia lembrar eu!
Very nice! Another way to achieve the same behaviour would be to order by a generated GUID:
values = values.OrderBy(v => Guid.NewGuid()).ToArray();
Cheers,
Caio Proiete
the nice thing about using Random is that you can use a seed like
Random r = new Random(DateTime.Now.Day) to return the same random sequence for a day.
Use Random, not Guid.NewGuid(), since guid cost more time.
eu adoro seu bolg acho muito maneiro só que no momento não pude escrever em inglês por que estava com pressapk depois me responde
these answers will work only for linq to objects not linq To Sql,
linq to sql send the new Guid or the rand number as a parameter to the sql,
it is better to do the order by after fetshing the data.
thanks
List list = objPTSMarketingDataContrxt..ToList();
return list.OrderBy(n => Guid.NewGuid()).ToList();
public static IEnumerable Randomize(this IEnumerable source)
{
Random rnd = new Random();
return source.OrderBy((item) => rnd.Next());
}