将文本文件数据隐藏到Datatable

时间:2016-01-18 10:47:03

标签: .net c#-4.0 datatable

我的文本文件包含此类数据。我想从文本文件中读取这些数据并将其转换为数据表。

FacilityID:   12787
FacilityName: ACME Medical Center
Facility Location: 
RecordID:            16611730-19049181-20529397-14136226
Patient:           Kistra Halos
Gender:            Female
DOB:               7/20/1955

在读取此输入时,它没有像我这样在数据表中显示输出

FacilityID:   12787
FacilityName: ACME Medical Center
Facility Location: 
RecordID:            16611730-19049181-20529397-14136226
Patient:           Kistra Halos
Gender:            Female
DOB:               7/20/1955

但我想要它:

FacilityID  FacilityName  Facility Location  RecordID  Patient  Gender  DOB
12787       ACME Medical                    16611730-. Kistra   Female 7/20/1955

var table = new DataTable();

    var fileContents = File.ReadAllLines(@"C:\simple.txt");

    var splitFileContents = (from f in fileContents select f.Split(':')).ToArray();

    int maxLength = (from s in splitFileContents select s.Count()).Max();

    for (int i = 0; i < maxLength; i++)
    {
        table.Columns.Add();
    }


    foreach (var line in splitFileContents)
    {
        DataRow row = table.NewRow();
        row.ItemArray = (object[])line;
        table.Rows.Add(row);
    }

我想对它执行搜索,排序操作。那么我如何转换呢。

1 个答案:

答案 0 :(得分:1)

您似乎可以在每一行中查找第一次出现的冒号。前面的部分是列名,后面的部分是值。

尝试这种方法:

DataTable table = new DataTable();
var lines = File.ReadLines(pathToFile).Where(l => l.Contains(':'));
foreach (string line in lines)
{
    int index = line.IndexOf(':');
    string column = line.Trim().Remove(index);
    string value = line.Trim().Substring(index + 1).Trim();
    DataColumn col = table.Columns[column];
    if (col == null)
        col = table.Columns.Add(column);
    bool isNewRecord = col.Ordinal == 0;
    DataRow row = isNewRecord ? table.Rows.Add() : table.Rows[table.Rows.Count - 1];
    row.SetField(column, value);
}

然后,您可以使用Linq-To-DataTable对表进行排序或查找特定行。

例如:

var rows = table.AsEnumerable().Where(row => row.Field<string>("FacilityID") == "12787");
DataRow firstRow = rows.FirstOrDefault();
if(firstRow != null)
{
     // for example:
     string patient = firstRow.Field<string>("Patient"); // Kistra Halos
     // ....
}