阅读随机行从一个文件? C# [英] Read random line from a file? c#

查看:192
本文介绍了阅读随机行从一个文件? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几百行的文本文件,其结构是pretty的简单。

名姓

我需要挑选出一个随机的名字和放大器;从文件LISTNAME。

解决方案

 字符串[]行= File.ReadAllLines(...); //我希望该文件不是太大
随机兰特=新的随机();
返回行[rand.Next(lines.Length)];
 

另外一个(也许更好)的选择是让该文件的第一行包含在里面的记录数,然后你就不必读取所有文件。

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.

解决方案

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.

这篇关于阅读随机行从一个文件? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆