2013-07-29 87 views
1

我从txt文件读取行。他们约有10万人。如何填补队列并改变其元素? 像这样填充队列:随机化一个队列

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(); 
     } 
    } 
+10

如果洗牌填写之后队列,比它仍然是一个真正的队列? –

+0

首先,'new Random.Next()'out? – MikeTheLiar

+0

这听起来像你正在寻找一个列表或数组 - 这不是一个队列的目的。 – tsells

回答

7

队列用于FIFO。你要求的东西其他比FIFO。所以,你正在使用错误的工具来完成这项工作。

一个简单的方法是用代替填写一个队列,填充一个列表,然后shuffle the elements of the list

-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) ; 

} 
0

如果你想有一个队列有从文件的随机配件行,那么你应该装满了文件的行列表,然后将它洗,然后后插入值将列表放入队列中,创建您所描述的最终结果。

0

这正与我的数组:

Queue<string> arrProvincies = new Queue<string>(File.ReadAllLines(@"provincies.txt").OrderBy(o => new Guid()));