简体   繁体   English

将请求正文转换为 C# 中的数据表或数据集

[英]Convert request body to datatable or dataset in C#

I am making a azure function that takes a request body.我正在制作一个带有请求正文的 azure function。 with the following format.具有以下格式。

"10","Name","112","50012","Activity","08/02/2021","3:20","3:10","" "10","Name","","","Break","08/02/2021"," - ","0:11","Break" "10","Name","112","50012","Activity","08/02/2021","2:09","2:09","" "10","姓名","112","50012","活动","08/02/2021","3:20","3:10","""10","姓名", "","","休息","08/02/2021"," - ","0:11","休息" "10","姓名","112","50012","活动" ,"08/02/2021","2:09","2:09",""

The first pair of strings is the worker ID, second is the name, 3rd is the id of the customer, 4th is the activity id, 5th is the activity, 6th is the date, 7th is the raw amount of hours worked, 8th is calculated amount of hours worked and last indicates if it was a break.第一对字符串是工人 ID,第二个是姓名,第三个是客户的 id,第四个是活动 id,第五个是活动,第六个是日期,第七个是原始工作小时数,第八个是计算的工作小时数和最后指示是否是休息时间。

Short there is 9 sets of string on each line and there is no telling how many lines there are.简而言之,每行有 9 组字符串,不知道有多少行。 Now i want to convert this to a datatable and then to a dataset.现在我想将其转换为数据表,然后转换为数据集。 So far i have only been able to read the body like this.到目前为止,我只能像这样阅读身体。

        using(var reader = new StreamReader(req.Body))
        {
            var ResponseBody = reader.ReadToEnd();

            return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
        }

I hope you can help me.我希望你能帮助我。 Thanks in advance.提前致谢。

I am suggesting you a sample approach and you can take this as reference for solving your actual problem.我建议您使用示例方法,您可以将其作为解决实际问题的参考。

So you have to read the data line by line and split the data.所以你必须逐行读取数据并拆分数据。

DataTable dt = new DataTable();
string[] columns = [];//column names as you have mentioned in your data there are no columns 
foreach (string column in columns)
{
    dt.Columns.Add(column);
}
using (StreamReader reader = new StreamReader(strFilePath))
{
    while (reader.EndOfStream == false)
    {
        string[] rows = reader.ReadLine().Split(',');
        DataRow dr = dt.NewRow();
        for (int i = 0; i < columns.Length; i++)
        {
            dr[i] = rows[i];
        }
        dt.Rows.Add(dr);
    }
}

Assumption: I'm assuming that you have no comma in between values假设:我假设您在值之间没有逗号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM