有一种简单的方法可以在VB.NET中将列表随机化吗? [英] Is there an easy way to randomize a list in VB.NET?

查看:46
本文介绍了有一种简单的方法可以在VB.NET中将列表随机化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型为System.IO.FileInfo的列表,我想将列表随机化.我以为我记得不久前见过类似list.randomize()之类的东西,但是我找不到我可能看到的地方.

I have a list of type System.IO.FileInfo, and I would like to randomize the list. I thought I remember seeing something like list.randomize() a little while back but I cannot find where I may have seen that.

我第一次涉足此功能使我具有以下功能:

My first foray into this yielded me with this function:

Private Shared Sub GetRandom(ByVal oMax As Integer, ByRef currentVals As List(Of Integer))
    Dim oRand As New Random(Now.Millisecond)
    Dim oTemp As Integer = -1
    Do Until currentVals.Count = IMG_COUNT
        oTemp = oRand.Next(1, oMax)
        If Not currentVals.Contains(oTemp) Then currentVals.Add(oTemp)
    Loop
End Sub

我向其发送要迭代的最大val,并向其中发送我希望将其随机化的内容的列表.变量IMG_COUNT在脚本中设置得更远,指定了我想要多少个随机图像显示.

I send it the max val I want it to iterate up to, and a reference to the list I want the randomized content in. The variable IMG_COUNT is set farther up in the script, designating how many random images I want displayed.

谢谢大家,我很感激:D

Thanks guys, I appreciate it :D

推荐答案

构建比较器:

Public Class Randomizer(Of T)
    Implements IComparer(Of T)

    ''// Ensures different instances are sorted in different orders
    Private Shared Salter As New Random() ''// only as random as your seed
    Private Salt As Integer
    Public Sub New()
        Salt = Salter.Next(Integer.MinValue, Integer.MaxValue)
    End Sub

    Private Shared sha As New SHA1CryptoServiceProvider()
    Private Function HashNSalt(ByVal x As Integer) As Integer
      Dim b() As Byte = sha.ComputeHash(BitConverter.GetBytes(x))
      Dim r As Integer = 0
      For i As Integer = 0 To b.Length - 1 Step 4
          r = r Xor BitConverter.ToInt32(b, i)
      Next

      Return r Xor Salt
    End Function

    Public Function Compare(x As T, y As T) As Integer _
        Implements IComparer(Of T).Compare

        Return HashNSalt(x.GetHashCode()).CompareTo(HashNSalt(y.GetHashCode()))
    End Function
End Class

假设您使用的是通用List(Of FileInfo):

list.Sort(New Randomizer(Of IO.FileInfo)())

您还可以使用闭包将随机值设置为粘性",然后仅在其上使用linq的.OrderBy()(这一次是C#,因为VB lambda语法很丑):

You can also use a closure to make the random value 'sticky' and then just use linq's .OrderBy() on that (C# this time, because the VB lambda syntax is ugly):

list = list.OrderBy(a => Guid.NewGuid()).ToList();

在这里说明原因,以及为什么它可能不如真正的随机播放那么快:
http://www.codinghorror.com/blog/archives/001008. html?r = 31644

Explained here, along with why it might not even be as fast as real shuffle:
http://www.codinghorror.com/blog/archives/001008.html?r=31644

这篇关于有一种简单的方法可以在VB.NET中将列表随机化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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