2016-04-05 30 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,因爲它會逐行評估文件,而不是將所有文件內容加載到內存中。