C# 把DataTable A,DataTable B,DataTable C,DataTable D里面相同的序列号的相关的数据用代码提取出来组成一行,一行一行组合,组成一个新的表,然后再和界面显示控件绑定
时间: 2023-12-14 07:39:13 浏览: 27
可以通过以下步骤来实现:
1. 将 A、B、C、D 四个 DataTable 合并成一个新的 DataTable E,可以使用 Merge 方法。
```csharp
DataTable E = new DataTable();
E.Merge(A);
E.Merge(B);
E.Merge(C);
E.Merge(D);
```
2. 定义一个 Dictionary<int, DataRow>,用于存储序列号对应的 DataRow。
```csharp
Dictionary<int, DataRow> dict = new Dictionary<int, DataRow>();
```
3. 遍历 DataTable E 中的每一行,将序列号作为 key,DataRow 作为 value 存入 Dictionary 中。
```csharp
foreach (DataRow row in E.Rows)
{
int key = Convert.ToInt32(row["序列号"]);
if (!dict.ContainsKey(key))
{
dict.Add(key, row);
}
}
```
4. 创建一个新的 DataTable F,用于存储提取后的数据。
```csharp
DataTable F = new DataTable();
```
5. 定义 DataTable F 的列,包括序列号和其他需要提取的列。
```csharp
F.Columns.Add("序列号", typeof(int));
F.Columns.Add("列1", typeof(string));
F.Columns.Add("列2", typeof(int));
// ...
```
6. 遍历 Dictionary,将每一个 DataRow 按照序列号组合成一行,并添加到 DataTable F 中。
```csharp
foreach (var pair in dict)
{
DataRow row = F.NewRow();
row["序列号"] = pair.Key;
row["列1"] = pair.Value["列1"];
row["列2"] = pair.Value["列2"];
// ...
F.Rows.Add(row);
}
```
7. 将 DataTable F 绑定到界面显示控件上。
```csharp
dataGridView.DataSource = F;
```
完整代码如下:
```csharp
DataTable E = new DataTable();
E.Merge(A);
E.Merge(B);
E.Merge(C);
E.Merge(D);
Dictionary<int, DataRow> dict = new Dictionary<int, DataRow>();
foreach (DataRow row in E.Rows)
{
int key = Convert.ToInt32(row["序列号"]);
if (!dict.ContainsKey(key))
{
dict.Add(key, row);
}
}
DataTable F = new DataTable();
F.Columns.Add("序列号", typeof(int));
F.Columns.Add("列1", typeof(string));
F.Columns.Add("列2", typeof(int));
// ...
foreach (var pair in dict)
{
DataRow row = F.NewRow();
row["序列号"] = pair.Key;
row["列1"] = pair.Value["列1"];
row["列2"] = pair.Value["列2"];
// ...
F.Rows.Add(row);
}
dataGridView.DataSource = F;
```