繁体   English   中英

在文本文件C#流阅读器中随机选择一行

[英]randomly select a line in a textfile c# streamreader

嗨,我正在从一个文本文件中读取内容,并希望将每一行放入一个单独的变量中。 根据我在编程类中所记得的,数组不可能是动态的。 因此,如果我设置15个数组,并且文本文件有1000行,那我该怎么做以及如何实现它。

事情只需要一行,但我希望该行是随机选择的。 linetext是整个文本文件,在每个请求的末尾附加\\ r \\ n。

也许随机选择\\ r \\ n,然后数4并在其后添加字符串,直到下一个\\ r \\ n。 这个想法的问题是被调用的字符串也将包含\\,所以有什么想法吗?

if (crawler == true)
   {
            TextReader tr = new StreamReader("textfile.txt");
            while (tr.Peek() != -1)
            {
                linktext = linktext + tr.ReadLine() + "\r\n";
            }

            //link = linktext;

            hi.Text = linktext.ToString();

            timer1.Interval = 7000; //1000ms = 1sec 7 seconds per cycle
            timer1.Tick += new EventHandler(randomLink); //every cycle randomURL is called.
            timer1.Start(); // start timer.
        }

File.ReadAllLines(...)将给定文件的每一行读入字符串数组。 我认为这应该是您想要的,但是您的问题有点难以理解。

您不需要一次在内存中保留两行以上...您可以使用一个偷偷摸摸的技巧:

  • 创建一个Random实例,或将其中一个作为参数
  • 阅读第一行。 这将自动成为要返回的“当前”行
  • 阅读第二行,然后调用Random.Next(2) 如果结果为0,则将第二行设为“当前”行
  • 阅读第三行,然后调用Random.Next(3) 如果结果为0,则将第三行设为“当前”行
  • ...等等
  • 当到达文件末尾时( reader.ReadLine返回null),返回“当前”行。

这是IEnumerable<T>的常规实现-如果使用的是.NET 4,则可以使用File.ReadLines()获得IEnumerable<string>传递给它。 (此实现中的内容比实际需要的要多得多-已针对IList<T>等进行了优化。)

public static T RandomElement<T>(this IEnumerable<T> source,
                                 Random random)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (random == null)
    {
        throw new ArgumentNullException("random");
    }
    ICollection collection = source as ICollection;
    if (collection != null)
    {
        int count = collection.Count;
        if (count == 0)
        {
            throw new InvalidOperationException("Sequence was empty.");
        }
        int index = random.Next(count);
        return source.ElementAt(index);
    }
    ICollection<T> genericCollection = source as ICollection<T>;
    if (genericCollection != null)
    {
        int count = genericCollection.Count;
        if (count == 0)
        {
            throw new InvalidOperationException("Sequence was empty.");
        }
        int index = random.Next(count);
        return source.ElementAt(index);
    }
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            throw new InvalidOperationException("Sequence was empty.");
        }
        int countSoFar = 1;
        T current = iterator.Current;
        while (iterator.MoveNext())
        {
            countSoFar++;
            if (random.Next(countSoFar) == 0)
            {
                current = iterator.Current;
            }
        }
        return current;
    }
}

List<T>是动态扩展的列表。 您可能要使用它而不是数组。

如果只有1000个元素,则将它们读入列表并选择一个随机元素。

关于数组的事情..您可以使用List <>代替,它是动态的

这是如何实现此目的的示例:

public static string GetRandomLine(ref string file) {
    List<string> lines = new List<string>();
    Random rnd = new Random();
    int i = 0;

    try {
        if (File.Exists(file)) {
            StreamReader reader = new StreamReader(file);
            while (!(reader.Peek() == -1))
                lines.Add(reader.ReadLine());
            i = rnd.Next(lines.Count);
            reader.Close();
            reader.Dispose();
            return lines[i].Trim();
        }
        else {
            return string.Empty;
        }
    }
    catch (IOException ex) {
        MessageBox.Show("Error: " + ex.Message);
        return string.Empty;
    }
}

如果创建文件,则理想的方法是事先存储有关文件的元数据(如行数),然后决定选择哪条“随机”行。

否则,不使用它们将无法解决“数组”问题。 而是使用存储任意数量字符串的列表。 之后,选择一个随机数就像生成一个介于0和列表大小之间的随机数一样简单。

您的问题之前已经解决过,建议您对“ C#从文件中读取随机行”进行谷歌搜索。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM