如何在使用 foreach 循环时添加到数据集中的特定列 C#

How to add to a specific column in a dataset while using a foreach loop c#

我正在尝试添加递增时间!列到我的数据网格视图以及从 streamreader 中提取的数据 'r';我有增量工作,但时间在行之间而不是在它们旁边。 数据显示如下:

15:46:20
91 154 70 309 83 6451

15:46:21
91 154 70 309 83 6451

当我想弄成这样的时候: 15:46:21 91 154 70 309 83 6451

                while ((r.Peek() != -1))
                {
                    string timeS = "";
                    string delimeter = "\t";
                    string[] Time1;
                    allData = r.ReadLine();
                    timeS = Dtime.ToString();
                    Time1 = timeS.Split(' ');
                    timeS = Time1[1];


                    string[] rows = allData.Split("\r".ToCharArray());

                    foreach (string row in rows)
                    {
                        Dtime = Dtime.AddSeconds(inter);
                        dataset.Tables[tableName].Rows.Add(timeS);
                        string[] items = row.Split(delimeter.ToCharArray());

                        dataset.Tables[tableName].Rows.Add(items);


                    }

                    this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
                }

干杯!

我认为问题是这样的:

dataset.Tables[tableName].Rows.Add(timeS);

其次是:

dataset.Tables[tableName].Rows.Add(items);

这就是添加两行的原因。

不过,还有一种更好的方法可以做到这一点。听起来好像您想动态添加另一列来保存时间值。这是在您的数据 table 中定义的,还是您在 运行 时添加的?无论哪种方式,它都需要存在才能保持价值。

我修改了上面的代码,将时间值放入项目数组的最后一个位置。它一点也不漂亮,可以大大简化。这是我的代码:

string timeS = "Time";
string row = "Value1,Value2,Value3";
string delimeter = ",";
string[] items = row.Split(delimeter.ToCharArray());
string[] newItems = new string[items.Length + 1];

items.CopyTo(newItems, 0);
newItems[newItems.Length - 1] = timeS;

现在你有了一个数组,其中最后一项是时间值。您可以将其添加到您的数据中 table:

dataTable.Rows.Add(newItems);

我相信有更好的方法可以做到这一点,也许这会帮助您朝着正确的方向前进。

与其将 timeS 本身添加为新行,不如将其添加为 items 数组中的第一项,然后将该数组添加为一行。

例如:

var items = new List<string>{timeS};
items.AddRange(row.Split(delimeter.ToCharArray()));                
dataset.Tables[tableName].Rows.Add(items.ToArray());