Read random line from a file? c#

后端 未结 2 679
我寻月下人不归
我寻月下人不归 2020-11-30 13:54

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 f

2条回答
  •  伪装坚强ぢ
    2020-11-30 14:46

    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.

提交回复
热议问题