C# 如何将文本文件中的数据显示到多个列中?
我有一个文本文件,它由许多行和18列数据组成,这些数据由选项卡分隔。我使用了这段代码,它在一列中显示整个数据。我需要的是数据应该显示在列中C# 如何将文本文件中的数据显示到多个列中?,c#,.net,tab-delimited,C#,.net,Tab Delimited,我有一个文本文件,它由许多行和18列数据组成,这些数据由选项卡分隔。我使用了这段代码,它在一列中显示整个数据。我需要的是数据应该显示在列中 public static List<string> ReadDelimitedFile(string docPath) { var sepList = new List<string>(); // Read the file and display it line by line. u
public static List<string> ReadDelimitedFile(string docPath)
{
var sepList = new List<string>();
// Read the file and display it line by line.
using (StreamReader file = new StreamReader(docPath))
{
string line;
while ((line = file.ReadLine()) != null)
{
var delimiters = new char[] { '\t' };
var segments = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (var segment in segments)
{
//Console.WriteLine(segment);
sepList.Add(segment);
}
}
file.Close();
}
// Suspend the screen.
Console.ReadLine();
return sepList;
}
公共静态列表ReadDelimitedFile(字符串docPath)
{
var sepList=新列表();
//读取文件并逐行显示。
使用(StreamReader文件=新StreamReader(docPath))
{
弦线;
而((line=file.ReadLine())!=null)
{
变量分隔符=新字符[]{'\t'};
var segments=line.Split(分隔符、StringSplitOptions.RemoveEmptyEntries);
foreach(分段中的var段)
{
//控制台写入线(段);
sepList.Add(段);
}
}
file.Close();
}
//暂停屏幕。
Console.ReadLine();
返回sepList;
}
您在一列中输出所有内容,如下所示(伪代码,用于说明结构):
也就是说,对于文件中的每一行以及该行中的每个条目,您都会输出一个新行。相反,您只希望为文件中的每一行写入新行,并使用分隔符(制表符?)写入条目。更像这样:
while (reading lines)
for (reading entries)
Write(entry)
WriteLine(newline)
var rows = new List<List<string>>();
foreach(var line in File.ReadAllLines(docPath))
{
var columns = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries).ToList();
rows.Add(columns);
}
这样,文件中任何给定行的所有条目都在输出的同一行上
当然,如何在输出中划分这些条目取决于您。编写回车可以像Console.WriteLine(string.Empty)一样简单,不过我敢打赌还有很多其他方法可以做到这一点。18列似乎最好使用dataGridView
// Create your dataGrodView with the 18 columns using your designer.
int col = 0;
foreach (var segment in segments)
{
//Console.WriteLine(segment);
//sepList.Add(segment);
dataGridView1.Rows[whateverRow].Cells[col].Value = segment;
}
您应该使用
DataTable
或类似的类型,但是如果您想使用List
您可以像这样“模拟”行和列:
while (reading lines)
for (reading entries)
Write(entry)
WriteLine(newline)
var rows = new List<List<string>>();
foreach(var line in File.ReadAllLines(docPath))
{
var columns = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries).ToList();
rows.Add(columns);
}
因此,根据您的代码,您有以下循环:
while{
<reads the lines one by one>
for each line{
<reading each segment and adding to the list.>
}
}
while{
每行{
}
}
代码读取行的每一段并附加到列表中。理想情况下,您应该有18个列表用于18列。在java中,可以使用hashmaps解决此问题:
Hashmap <String, ArrayList<String>> hmp = new Hashmap<String, ArrayList<String>>();`
while(read each line){
List<String> newList = new ArrayList<String>
foreach(segment as segments){
newList.add(segment);
}
hmp.put(column1,segment);
}
return hmp;
Hashmap hmp=newhashmap()`
while(读每行){
List newList=newarraylist
foreach(段作为段){
添加(段);
}
hmp.put(第1列,段);
}
返回hmp;
因此,您将有hmp.put(第2列,段)
,hmp.put(第3列,段)
等等
希望有帮助。您不能使用一些支持列的对象/集合,例如DataTable吗?