高效的功能,用于读取分隔文件到数据表 [英] Efficient function for reading a delimited file into DataTable
本文介绍了高效的功能,用于读取分隔文件到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有人知道一个高效的C#函数用于读取制表符分隔文件转换成一个DataTable?
I was wondering if anyone knew of an efficient c# function for reading a tab delimited file into a datatable?
感谢
推荐答案
本目前使用LINQ方法。首先()和
.Skip()`都是容易如果你需要使用.Net的2.0重现
This currently uses the LINQ methods .First()' and
.Skip()` both are easy to recreate if you need to use this on .Net 2.0
//even cooler as an extension method
static IEnumerable<string> ReadAsLines(string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
static void Main()
{
var filename = "tabfile.txt";
var reader = ReadAsLines(filename);
var data = new DataTable();
//this assume the first record is filled with the column names
var headers = reader.First().Split('\t');
foreach (var header in headers)
data.Columns.Add(header);
var records = reader.Skip(1);
foreach (var record in records)
data.Rows.Add(record.Split('\t'));
}
这篇关于高效的功能,用于读取分隔文件到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文