开发者

Read random line from a file? c#

开发者 https://www.devze.com 2023-01-16 22:50 出处:网络
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 开发者_Python百科file. string[] lines = Fi

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 开发者_Python百科file.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消