3

我从 txt 文件中读取行。它们大约是 100 000。如何填充队列并打乱其元素?像这样填充队列:

    Queue<string> accs = new Queue<string>();
    private void loadLikeAccountsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            accs.Clear();

            foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
            {
                accs.Enqueue(s);
            }
            label4.Text = accs.Count.ToString();
        }
    }
4

4 回答 4

7

队列用于 FIFO。您要求的不是FIFO。所以,你使用了错误的工具来完成这项工作。

一个简单的方法是填充一个列表,而不是填充一个列表,然后打乱列表中的元素

于 2013-07-29T19:06:41.000 回答
1

这适用于我的数组:

Queue<string> arrProvincies = new Queue<string>(File.ReadAllLines(@"provincies.txt").OrderBy(o => new Guid()));
于 2016-09-12T13:52:51.690 回答
0

如果您希望队列具有来自文件随机部分的行,那么您应该用文件的行填充一个列表,然后对其进行洗牌,然后将列表插入队列中,创建您所描述的最终结果。

于 2013-07-29T19:40:07.543 回答
-1

尝试这样的事情:

class Program
{
  static void Main( string[] args )
  {
    string myFileName = @"c:\foo\bar\baz.txt" ;
    Queue<string> queue = new Queue<string>( File.ReadAllLines(myFileName).Shuffle() ) ;
  }
}
/// <summary>
/// A few helper methods
/// </summary>
static class ExtensionMethods
{
  /// <summary>
  /// Performs an in-place shuffle of an array
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="instance"></param>
  /// <returns></returns>
  public static T[] Shuffle<T>( this T[] instance )
  {
    for ( int i = 0 ; i < instance.Length ; ++i )
    {
      int j = rng.Next(i,instance.Length ) ; // select a random j such that i <= j < instance.Length

      // swap instance[i] and instance[j]
      T x = instance[j] ;
      instance[j] = instance[i] ;
      instance[i] = x ;

    }

    return instance ;
  }
  private static readonly Random rng = new Random() ;

}

但为什么要使用Queue<T>? 有吗?这样的事情更简单,更直接:

List<string> shuffledLines = new List<string>( File.ReadAllLines(fn).Shuffle() ) ;
.
.
.
// we iterate over the shuffled list in reverse order so as to 
// shrink the list in place rather than remove the leftmost item
// and moving the remainder wholesale on each iteration.
for ( int i = --shuffledLines.Length ; i >= 0 ; --i )
{
  string s = shuffledLines(i) ;
  shuffledLines.RemoveAt(i) ;

  DoSomethingUseful( s ) ;

}
于 2013-07-29T19:18:58.710 回答