我有一个c#问题:我有两个数据表A和B,它们都包含一个名为“move”的列,我想创建另一个包含两个列的数据表,一个包含来自A的“move”,另一个包含来自B的“move”,我尝试了类似这样的操作:
//cherche les last price
DataTable TickerPrice = new DataTable("Data");
TickerPrice = CheckBloomi(TickerName + " equity", "CHG_PCT_1D", FromThisTime, ToThisTime);
//cherche les last price
DataTable IndexPrice = new DataTable("Data");
IndexPrice = CheckBloomi("E300 Index", "CHG_PCT_1D", FromThisTime, ToThisTime);
DataSet MarketData = new DataSet();
DataTable Recap = MarketData.Tables.Add("Recap");
Recap.Columns.Add("Move Ticker price");
Recap.Columns.Add("Move Index price");
foreach (DataRow sourcerow in TickerPrice.Rows)
{
DataRow destRow = Recap.NewRow();
destRow["Move Ticker price"] = sourcerow["CHG_PCT_1D"];
Recap.Rows.Add(destRow);
}
foreach (DataRow sourcerow in IndexPrice.Rows)
{
DataRow destRow = Recap.NewRow();
destRow["Move Index price"] = sourcerow["CHG_PCT_1D"];
Recap.Rows.Add(destRow);
}这可以很好地复制一列(对于第一个foreach循环),但是对于第二列,我将数字移位,因为我正在重新创建新的行。
你知道怎么做吗?如果还不够清楚,请告诉我。
发布于 2011-11-24 00:49:11
假设TicketPrice和IndexPrice表都匹配,那么您可以这样做:
for (int i = 0; i < TickerPrice.Rows.Count; i++)
{
DataRow destRow = Recap.NewRow();
destRow["Move Ticker price"] = TickerPrice.Rows[i]["CHG_PCT_1D"];
destRow["Move Index price"] = IndexPrice.Rows[i]["CHG_PCT_1D"];
Recap.Rows.Add(destRow);
}发布于 2011-11-24 00:44:30
你能不能把NewRow()和Rows.Add()从内部循环中去掉?如下所示:
DataRow destRow = Recap.NewRow();
foreach (DataRow sourcerow in TickerPrice.Rows)
{
destRow["Move Ticker price"] = sourcerow["CHG_PCT_1D"];
}
foreach (DataRow sourcerow in IndexPrice.Rows)
{
destRow["Move Index price"] = sourcerow["CHG_PCT_1D"];
}
Recap.Rows.Add(destRow);这里假设TickerPrice.Rows和IndexPrice.Rows中的值是一致的。
https://stackoverflow.com/questions/8245794
复制相似问题