2016-04-05 31 views
1

我有一个function读取所有从一个文本文件中的tab delimited记录成datatble,但我有很多空或空列也该是tab delimited。我只想读取列3不为空或非空的所有记录。我该怎么做? 这里是我的简单的方法不从文本文件中读入datatble空或空记录 - C#

public DataTable ConvertTextToDataTable(string filePath, int numberOfColumns) 
    { 
     DataTable tbl = new DataTable(); 

     for (int col = 0; col < numberOfColumns; col++) 
      tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString())); 


     string[] lines = System.IO.File.ReadAllLines(filePath); 
     int i = 0; 
     foreach (string line in lines) 
     { 
      var cols = line.Split('\t'); 

      DataRow dr = tbl.NewRow(); 
      for (int cIndex = 0; cIndex < numberOfColumns; cIndex++) 
      { 
       dr[cIndex] = cols[cIndex]; 
      } 

      tbl.Rows.Add(dr); 
      i++; 
     } 
     return tbl; 
    } 
+0

除了Habibs的答案你可以看看[TextFieldParser](https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser%28v=vs.110%29.aspx)阅读和分裂。 – Filburt

回答

2

最简单的将是插入了IsNullOrWhiteSpace列3检查创建和并添加值,如数据表之前:

public DataTable ConvertTextToDataTable(string filePath, int numberOfColumns) 
{ 
    DataTable tbl = new DataTable(); 

    for (int col = 0; col < numberOfColumns; col++) 
     tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString())); 


    var lines = System.IO.File.ReadLines(filePath); 
    int i = 0; 
    foreach (string line in lines) 
    { 
     var cols = line.Split('\t'); 

     if (cols.Length > 3 && String.IsNullOrWhiteSpace(cols[3])) 
     { 
      continue; //Ignore this line 

     } 
     DataRow dr = tbl.NewRow(); 
     for (int cIndex = 0; cIndex < numberOfColumns; cIndex++) 
     { 
      dr[cIndex] = cols[cIndex]; 
     } 

     tbl.Rows.Add(dr); 
     i++; 
    } 
    return tbl; 
} 

还要注意使用var lines = System.IO.File.ReadLines(filePath);而不是File.ReadAllLines,因为它会逐行评估文件,而不是将所有文件内容加载到内存中。