将分隔文件读入DataTable的高效函数 [英] Efficient function for reading a delimited file into DataTable

查看:40
本文介绍了将分隔文件读入DataTable的高效函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道将制表符分隔的文件读入数据表的高效 c# 函数?

I was wondering if anyone knew of an efficient c# function for reading a tab delimited file into a datatable?

谢谢

推荐答案

目前使用的 LINQ 方法 .First().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('	');
    foreach (var header in headers)
        data.Columns.Add(header);

    var records = reader.Skip(1);
    foreach (var record in records)
        data.Rows.Add(record.Split('	'));
}

这篇关于将分隔文件读入DataTable的高效函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆