我们如何将字符串数据转换为数据表?

时间:2016-01-12 10:46:37

标签: c# parsing datatable

我需要将字符串数据转换为datatable。

在单个字符串中获取整个数据。

sffa

S.No  Name   Address  Company
----  ----   -------  -------
 1     xxx    yyy     zzz
 2     vvv    nnn     dsd

以下是获取上述数据的代码

public string Read()
    {
        if (!tcpSocket.Connected) return null;
        StringBuilder sb=new StringBuilder();
        do
        {
            ParseTelnet(sb);

            System.Threading.Thread.Sleep(TimeOutMs);
        } while (tcpSocket.Available > 0);
        var strResult=sb.ToString();
        return strResult;
    }

我想要S.No,姓名,地址,公司作为列,这些值应该在适当的列中。

请提前帮助和致谢。

2 个答案:

答案 0 :(得分:0)

假设tab是分隔符:

IEnumerable<string[]> data = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Select(line => line.Split('\t'))
    .Where(fields => fields.Length == 4)
    .ToList();
DataTable table = new DataTable();
foreach(string col in data.First())
    table.Columns.Add(col);
foreach (string[] fields in data.Skip(1))
    table.Rows.Add(fields);

如果分隔符是一个或多个空格,并且值本身不能包含空格:

IEnumerable<string[]> data = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Select(line => line.Trim().Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries))
    .Where(fields => fields.Length == 4)
    .ToList();

答案 1 :(得分:0)

        string data = @"S.No  Name   Address  Company
----  ----   -------  -------
 1     xxx    yyy     zzz
 2     vvv    nnn     dsd";

        var lines = data.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
        var lengths = lines[1] + " "; //We'll think the dashes are the column markers.

        var insideColumn = false;
        int start = 0;
        var columns = new List<Tuple<int, int>>();
        for (int i = 0; i < lengths.Length; i++) {
            if (insideColumn && lengths[i] == ' ') {
                insideColumn = false;
                columns.Add(Tuple.Create(start, i));
            }
            if (!insideColumn && lengths[i] == '-') {
                insideColumn = true;
                start = i;
            }
        }

        var headers = new List<string>(columns.Count);
        for (int i = 0; i < columns.Count; i++) {
            headers.Add(lines[0].Substring(columns[i].Item1, columns[i].Item2 - columns[i].Item1).Trim());
        }

        var table = new List<Dictionary<string,string>>();
        for (int i = 2; i < lines.Length; i++) {
            var record = new Dictionary<string, string>();
            var line = lines[i].PadRight(lengths.Length);
            for (int j = 0; j < columns.Count; j++) {
                record[headers[j]] = line.Substring(columns[j].Item1, columns[j].Item2 - columns[j].Item1).Trim();
            }
            table.Add(record);
        }