Read random line from a file? c#

后端 未结 2 684
我寻月下人不归
我寻月下人不归 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:33

    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.

提交回复
热议问题