随机化与.NET数组的最佳方法 [英] Best way to randomize an array with .NET

查看:169
本文介绍了随机化与.NET数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是随机的。NET字符串数组的最佳方式?我的数组包含了约500串,我想创建一个新的阵列具有相同的字符串,但在一个随机顺序。

What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new Array with the same strings but in a random order.

请在你的答案是C#示例。

Please include a C# example in your answer.

推荐答案

如果你在.NET 3.5中,可以使用下面的IEnumerable冷静(VB.NET,而不是C#,但这个想法应该是清楚的... ):

If you're on .NET 3.5, you can use the following IEnumerable coolness (VB.NET, not C#, but the idea should be clear...):

Random rnd=new Random();
string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();    

编辑:好了,这里是对应的VB.NET code:

OK and here's the corresponding VB.NET code:

Dim rnd As New System.Random
Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next)

二编辑,针对言论System.Random不是线程安全和只适用于玩具的应用由于返回一个基于时间序列:在我的例子中使用,随机()是完全线程安全的,除非你允许在其中随机数组的例程重新输入,在这种情况下,你需要像锁(MyRandomArray)反正为了不要破坏你的数据,这将保护 RND 为好。

Second edit, in response to remarks that System.Random "isn't threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like lock (MyRandomArray) anyway in order not to corrupt your data, which will protect rnd as well.

此外,应该充分理解的是,作为System.Random熵的源不是很强。正如 MSDN文档指出,你应该使用的东西从 System.Security.Cryptography.RandomNumberGenerator 如果你做任何事情与安全相关的。例如:

Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the MSDN documentation, you should use something derived from System.Security.Cryptography.RandomNumberGenerator if you're doing anything security-related. For 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]);
    }

这篇关于随机化与.NET数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆