我正在阅读一个包含两列(包含x和y坐标)的文本文件:
static void Main(string[] args)
{
string line;
using (StreamReader file = new StreamReader(@"C:\Point(x,y).txt"))
{
while ((line = file.ReadLine()) != null)
{
char[] delimiters = new char[] { '\t' };
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
}
}
// Suspend the screen.
Console.ReadLine();
我想在两个不同的变量中分别读取文本文件中的数据 如何访问每个值?
答案 0 :(得分:0)
这是Linq可以救援的案例。您可以阅读所有行并直接使用Linq进行解析。我假设你有一个基于行的制表符分隔文本文件。你正在做的Split。您可以创建一个新的匿名类型来捕获文本文件中的行/行。然后,您可以通过循环遍历列表中的每个项目/匿名类型来访问在写入控制台时看到的字段。确保包含使用的System.Linq命名空间,默认情况下通常存在。
var records = File
.ReadAllLines(@"C:\Users\saira\Documents\Visual Studio 2017\Projects\Point(x,y).txt")
.Select(record => record.Split('\t'))
.Select(record => new
{
x = record[0],
y = record[1]
}).ToList();
foreach (var record in records)
{
Console.WriteLine($"The x coordinate is:{record.x}, and the y coordinate is {record.y}");
}