c# - 如何生成具有以下结果的 DataTable?
问题描述
我已经使用 OleDb 从用户上传中检索了两个 excel 文件。我产生了以下结果:
| Location | Item Type | AmountA | AmountB | Type |
| A | A | 5 | 4 | |
但我想产生以下结果:
| Location | Item Type | AmountA | AmountB | Type |
| A | A | 5 | | A |
| A | A | | 4 | B |
这些是我的代码:
public DataTable CombineofAdjustmentNTransaction(DataTable A, DataTable B)
{
DataTable TableE = new DataTable();
TableE.Columns.Add(new DataColumn("Location"));
TableE.Columns.Add(new DataColumn("Item Type"));
TableE.Columns.Add(new DataColumn("AmountA)"));
TableE.Columns.Add(new DataColumn("AmountB"));
TableE.Columns.Add(new DataColumn("TransactionType"));
foreach (DataRow dtE in A.Rows)
{
foreach (DataRow rowB in B.Rows)
{
if (rowB["Location"].ToString() == dtE["Location"].ToString() && rowB["Item Type"].ToString() == dtE["Item Type"].ToString()
)
{
var newRow = TableE.NewRow();
newRow["Location"] = dtE["Location"];
newRow["Item Type"] = dtE["Item Type"];
if(dtE["Type"].ToString() == "GRN")
{
newRow["AmountA"] = dtE["AmountA"];
newRow["Type"] = "GRN";
}
if (rowB["Type"].ToString() == "STK_ADJ")
{
newRow["AmountB"] = rowB["AmountB"];
newRow["Type"] = "STK_ADJ";
}
TableE.Rows.Add(newRow);
}
}
}
return TableE;
}
}
请帮忙谢谢!
解决方案
public DataTable CombineofAdjustmentNTransaction(DataTable A, DataTable B)
{
DataTable TableE = new DataTable();
TableE.Columns.Add(new DataColumn("Location"));
TableE.Columns.Add(new DataColumn("Item Type"));
TableE.Columns.Add(new DataColumn("AmountA"));
TableE.Columns.Add(new DataColumn("AmountB"));
TableE.Columns.Add(new DataColumn("Type"));
foreach (DataRow dtE in A.Rows)
{
foreach (DataRow rowB in B.Rows)
{
if (rowB["Location"].ToString() == dtE["Location"].ToString() && rowB["Item Type"].ToString() == dtE["Item Type"].ToString()
)
{
var newRow = TableE.NewRow();
newRow["Location"] = dtE["Location"];
newRow["Item Type"] = dtE["Item Type"];
if (dtE["Type"].ToString() == "GRN")
{
newRow["AmountA"] = dtE["AmountA"];
newRow["Type"] = "A";
}
if (rowB["Type"].ToString() == "STK_ADJ" && newRow["AmountA"].ToString() != "" && newRow["AmountA"].ToString() != "")
{
var BNewRow = TableE.NewRow();
BNewRow["Location"] = rowB["Location"];
BNewRow["Item Type"] = rowB["Item Type"];
BNewRow["AmountB"] = rowB["AmountB"];
BNewRow["Type"] = "B";
TableE.Rows.Add(BNewRow);
}
else {
newRow["AmountB"] = rowB["AmountB"];
newRow["Type"] = "B";
}
TableE.Rows.Add(newRow);
}
}
}
return TableE;
}
推荐阅读
- java - 编写 checkOrElseThrow 泛型函数的更好方法
- bash - 考虑下载文件的特定名称
- android-layout - 在 Gridview.count 之后放置一个按钮 - Flutter
- javascript - 多个复选框动作
- asp.net-mvc - 从控制器中的模型访问数据?
- c# - 实体框架数据类
- python-3.x - 如何检查文件是否已关闭?蟒蛇3
- android - 几个位置后的自定义gridview显示不正确的数据
- c# - 如何以 Html 形式绑定 Ajax 数据
- javascript - Error importing component from forked npm package