Read random line from a file? c#

馋奶兔 提交于 2019-12-17 07:54:46

问题


I have a text file with few hundred lines, the structure is pretty simple.

firstname lastname

I need to pick out a random firstname & listname from the file.


回答1:


string[] lines = File.ReadAllLines(...); //i hope that the file is not too big
Random rand = new Random();
return lines[rand.Next(lines.Length)];

Another (and maybe better) option is to have the first line of the file contain the number of records in it and then you don't have to read all the file.




回答2:


Read each line keeping a count, N, of the lines you have seen so far. Select each line with probability 1/N, i.e., the first line will always be chosen, the second line will be chosen 1/2 times to replace the first, the third 1/3 times, ... This way each line has a 1/N probability of being the selected line, you only have to read the file once, and you don't need to store all of the file in memory at any given time.

Here's an implementation that can be adapted for your needs.

public string RandomLine( StreamReader reader )
{
    string chosen = null;
    int numberSeen = 0;
    var rng = new Random();
    while ((string line = reader.ReadLine()) != null)
    {
        if (rng.NextInt(++numberSeen) == 0)
        {
            chosen = line;
        }
    }
    return chosen;
}

Based on a C implementation for selecting a node from an arbitrarily long linked list.



来源:https://stackoverflow.com/questions/3745934/read-random-line-from-a-file-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!