我有一个文本文件,其中包含许多行和18列数据,这些数据由制表符分隔。我使用了这段代码,它在单列中显示整个数据。我需要的是数据应该显示在列中。
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;
}
答案 0 :(得分:0)
您正在输出一行中的所有内容(伪代码,以说明结构):
while (reading lines)
for (reading entries)
WriteLine(entry)
也就是说,对于文件中的每一行以及该行中的每个条目,都会输出一个新行。相反,您只想为文件中的每一行写一个新行,并使用分隔符(制表符?)编写条目。更像是这样:
while (reading lines)
for (reading entries)
Write(entry)
WriteLine(newline)
这样,文件中任何给定行的所有条目都在输出的同一行。
当然,如何在输出中界定这些条目取决于您。写回车可能就像Console.WriteLine(string.Empty)
一样简单,但我敢打赌还有很多其他方法可以做到。
答案 1 :(得分:0)
使用dataGridView似乎可以最好地提供18列。
// 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;
}
答案 2 :(得分:0)
您应该使用DataTable
或类似的类型,但如果您想使用List
,则可以“模拟”这样的行和列:
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);
}
这将为您提供类似行/列的结构
foreach(var row in rows)
{
foreach(var column in row)
{
Console.Write(column + ",");
}
Console.WriteLine();
}
答案 3 :(得分:0)
因此,根据您的代码,您有以下循环:
while{
<reads the lines one by one>
for each line{
<reading each segment and adding to the list.>
}
}
您的代码会读取一行的每个段并附加到列表中。理想情况下,您应该有18列18列表。在java中,这个问题可以通过哈希映射来解决:
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;
因此您将拥有hmp.put(column2, segment)
,hmp.put(column3, segment)
等等。
希望它有所帮助。