【问题标题】:Input array is longer than the column in the table in txt dataset输入数组比txt数据集中表中的列长
【发布时间】:2015-06-02 17:49:29
【问题描述】:

我是 C# 新手,我想知道如何从 txt 数据集中提取数据并将其放入 c# 数据集中并使用它执行一些计算。

这就是我的数据集的样子

5.982   0.228   0.237   0.221   0.222   0.527
2.13    0.262   0.273   0.251   0.254   0.427   

这是我的业余代码:

string file = "D://test1.txt";
string tableName = "table";
string delimiter = "\t";

DataSet ds = new DataSet();
StreamReader s = new StreamReader(file);

ds.Tables.Add(tableName);

string AllData = s.ReadToEnd();

foreach (string r in rows)
{
    string[] items = r.Split(delimiter.ToCharArray());
    ds.Tables[TableName].Rows.Add(items);
}

int MaxRows = ds.Tables[0].Rows.Count;
Console.Write(MaxRows);
Console.ReadLine();

它总是显示错误:

输入数组长于该表的列数。

【问题讨论】:

  • 您定义了 0 列的表。首先定义它们。
  • 我只想以行方式访问数据。对我来说只有 1 列足够。而且我不知道如何定义一列。
  • 看来这是您今天第二次发布此问题了。以后,请编辑您的问题,而不是发布新问题。

标签: c# dataset


【解决方案1】:

您必须先添加一些列来保存数据。比如:

var tableName = "MyTableName";
DataTable table = ds.Tables.Add(tableName);

table.Columns.Add("firstColumnName", typeof(string));
table.Columns.Add("secondColumnName", typeof(string));
table.Columns.Add("thirdColumnName", typeof(string));
table.Columns.Add("fourthColumnName", typeof(string));
table.Columns.Add("fifthColumnName", typeof(string));
table.Columns.Add("sixthColumnName", typeof(string));

作为如何向该表添加行的示例:

const string dataFilePath = @"d:\public\temp\data.txt";
string[] fileData = File.ReadAllLines(dataFilePath);
var numColumns = table.Columns.Count;

foreach (string dataItem in fileData)
{
    var items = dataItem.Split(delimiter.ToCharArray()).Take(numColumns);
    table.Rows.Add(items);
}

【讨论】:

  • 我已经在代码中添加了这个,但仍然遇到同样的错误。 'ds.Tables[TableName].Columns.Add("column1",typeof(string));'
  • 好吧,这不是我发布的代码......大写的TableName在哪里定义?
  • 更新了添加行的示例。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2019-03-27
  • 2018-08-21
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多