c# - Best way to randomize an array with .NET -
what best way randomize array of strings .net? array contains 500 strings , i'd create new array
same strings in random order.
please include c# example in answer.
if you're on .net 3.5, can use following ienumerable coolness (vb.net, not c#, idea should clear...):
random rnd=new random(); string[] myrandomarray = myarray.orderby(x => rnd.next()).toarray();
edit: ok , here's corresponding vb.net code:
dim rnd new system.random dim myrandomarray = myarray.orderby(function() rnd.next)
second edit, in response remarks system.random "isn't threadsafe" , "only suitable toy apps" due returning time-based sequence: used in example, random() thread-safe, unless you're allowing routine in randomize array re-entered, in case you'll need lock (myrandomarray)
anyway in order not corrupt data, protect rnd
well.
also, should well-understood system.random source of entropy isn't strong. noted in msdn documentation, should use derived system.security.cryptography.randomnumbergenerator
if you're doing security-related. example:
using system.security.cryptography;
...
rngcryptoserviceprovider rnd = new rngcryptoserviceprovider(); string[] myrandomarray = myarray.orderby(x => getnextint32(rnd)).toarray();
...
static int getnextint32(rngcryptoserviceprovider rnd) { byte[] randomint = new byte[4]; rnd.getbytes(randomint); return convert.toint32(randomint[0]); }
Comments
Post a Comment