[英]binding comma seperated values into a datatable c#
我的问题与“ 如何在C#中将逗号分隔的字符串添加到数据表”中提到的有些相同?
但是在我的情况下,列数不是固定的。 高是最高值,其他是不同时间间隔的值。
因此,我必须显示直到午夜的值...就像用户选择下午1点一样,我必须显示从下午1点到午夜的所有值。因此,用户选择的内容会有所不同,他们可以选择凌晨2点至凌晨4点,依此类推的列数会有所不同。
产品名称高15:00 14:45 14:30 14:15 14:00 13:45 13:30 ...产品1 12 10 10 10 10 10 10 12 0 n产品2 10 10 0 0 0 0 0 0 n产品3 10 10 10 10 10 10 5 5 n
我能够以逗号分隔值的形式绑定数据,但如何绑定到我不了解的数据表中。
我的逗号分隔值有点像从15:45到午夜,如果我们认为用户选择了15小时。
产品1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 |
产品2,9.00,1,1,1,9.00,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 |
这样的代码怎么样
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
string[] inputs = {
"Product1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
"Product2,9.00,1,1,1,9.00,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1"
};
List<List<string>> data = new List<List<string>>();
foreach (string input in inputs)
{
List<string> newData = input.Split(new char[] { ',' }).ToList();
data.Add(newData);
}
DataTable dt = new DataTable();
int maxRows = data.Select(x => x.Count).Max();
for(int column = 0; column < data.Count; column++)
{
dt.Columns.Add(data[column][0], typeof(string));
dt.Columns[column].AllowDBNull = true;
}
for (int row = 0; row < maxRows; row++)
{
dt.Rows.Add();
}
for (int column = 0; column < data.Count; column++)
{
for (int row = 0; row < data[column].Count; row++)
{
dt.Rows[row][column] = data[column][row];
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.