读取随机行

本文关键字:随机 读取 | 更新日期: 2023-09-27 17:53:29

是否有办法使StreamReader ReadLine()随机顺序通过CSV文件?

的例子:

StreamReader reader = new StreamReader(File.OpenRead(@"C:''file.csv"));
String firstName = reader.ReadLine().ToString();
Console.WriteLine(firstName);

读取随机行

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();

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)]);
}

使用c#的Random类生成一个随机数,您将使用它从文件中选择一行。

file . readlines()不必读取整个文件,您可以使用LINQ构建查询来过滤它读取的行:

返回值类型:System.Collections.Generic.IEnumerable All文件的行,或作为查询结果的行。

然而,在本例中,我们需要全部读取以找到行数。

// 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();