有没有办法通过CSV文件以随机顺序制作StreamReader ReadLine()
?StreamReader阅读随机行
例子:
StreamReader reader = new StreamReader(File.OpenRead(@"C:\\file.csv"));
String firstName = reader.ReadLine().ToString();
Console.WriteLine(firstName);
有没有办法通过CSV文件以随机顺序制作StreamReader ReadLine()
?StreamReader阅读随机行
例子:
StreamReader reader = new StreamReader(File.OpenRead(@"C:\\file.csv"));
String firstName = reader.ReadLine().ToString();
Console.WriteLine(firstName);
的使用C#Random类来生成您可以使用它来选择你的文件中的行的随机数。
File.ReadLines()不必读取整个文件,你可以使用LINQ来构建查询来筛选它读取行:
返回值类型:System.Collections.Generic.IEnumerable所有 的文件的行或查询结果的行。
但是,在这种情况下,我们需要全部阅读才能找到行数。
// Read lines
string[] lines = File.ReadLines(@"C:\file.csv");
// Seed a random number in the range 0 to your count
var r = new Random();
int randomNumber = r.Next(0, lines.Length);
// Read the random line
string line = lines.Skip(randomNumber - 1).Take(1).First();
的StreamReader
是只能向前,没有办法,你可以倒着走,但你可以阅读所有线路到内存中首先使用File.ReadAllLines
:
string[] allLines = File.ReadAllLines(@"C:\\file.csv");
Random rnd = new Random();
List<string> randomLines = new List<string>(allLines.Length);
for(int i = 0; i < allLines.Length ; i++)
{
randomLines.Add(allLines[rnd.Next(allLines.Length)]);
}
的StreamReader读取每个定义顺序。我能想到的是如果文件不是很大
var lines File.ReadAllLines(@"C:\\file.csv")
Random random = new Random((int)DateTime.Now.Millisecond);
List<T> sortedList = lines.OrderBy(x => random.Next()).ToList();
如果你的随机数大于你的线数呢? –
没关系。随机数字仅用于排序行。所以实际上它只是获取线条,然后为其分配一个随机数字。 – Murdock
我明白了。我不知道如果阅读一个大文件,然后命令所有行选择一个随机行是最好的主意? –
是的。也许你可以告诉我们你试过了什么? –
你能把整个文件一次加载到内存中吗?如果你可以很容易,如果你不能这么做,或者非常缓慢或烦人的代码。 – CodesInChaos