我正在使用由xml文件导入的数据表
因此,我将多个数据表合并到一个数据表中,获取具有相同代理名称的行,并将每列的值添加到一个数据行,并将其放在新表上,并将其显示在数据网格视图中 实施例
输入:
Agent Product1 Product2
A 1 3
B 4 5
A 5 4
输出:
Agent Product1 Product2
A 6 7
B 4 5
答案 0 :(得分:0)
使用Linq:
onCreate
答案 1 :(得分:0)
试试这个
DataTable dt1 = new DataTable();
dt1.Columns.Add("Agent", typeof(string));
dt1.Columns.Add("Product1", typeof(int));
dt1.Columns.Add("Product2", typeof(int));
dt1.Rows.Add(new object[] {"A", 1, 3});
dt1.Rows.Add(new object[] {"B", 4, 5});
dt1.Rows.Add(new object[] {"A", 5, 4});
DataTable dt2 = dt1.Clone();
var sum = dt1.AsEnumerable()
.GroupBy(x => x.Field<string>("Agent"))
.Select(m => new
{
key = m.Key,
p1 = m.Sum(s => s.Field<int>("Product1")),
p2 = m.Sum(s => s.Field<int>("Product2"))
}).ToList();
foreach (var row in sum)
{
dt2.Rows.Add(new object[] { row.key, row.p1, row.p2 });
}
dataGridView1.DataSource = dt2;
答案 2 :(得分:0)
希望这就是您要找的东西:)只需将您的数据表传递给 dt ,您就会在 dtFinal
中找到所需的输出 DataTable dt = new DataTable();
dt.Columns.Add("Agent");
dt.Columns.Add("Product1");
dt.Columns.Add("Product2");
DataRow dr = dt.NewRow();
dr[0] = "AA";
dr[1] = 7;
dr[2] = 5;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "AA";
dr[1] = 5;
dr[2] = 6;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "BB";
dr[1] = 2;
dr[2] = 3;
dt.Rows.Add(dr);
DataView view = new DataView(dt);
DataTable dtDaysInDocument = view.ToTable(true, "Agent");**//Used to distinct column value**
string[] dateRecord = dtDaysInDocument.Rows.Cast<DataRow>()
.Select(row => row["Agent"].ToString())
.ToArray();
DataTable dtFinal = new DataTable();
dtFinal = dt.Clone();
foreach (string str in dateRecord)
{
DataRow[] rows = dt.Select("Agent='" + str + "'");
if (rows.Length > 1)
{
int finalValue = 0;
foreach (DataColumn col in dt.Columns)
{
if (col.ColumnName != "Agent")
{
foreach (DataRow row in rows)
{
int colValue = row[col] != null ? Convert.ToInt16(row[col]) : 0;
finalValue = colValue;
DataRow[] dtFinalrows = dtFinal.Select("Agent='" + str + "'");
if (dtFinalrows.Length == 1)
{
string val = dtFinalrows[0][col.ColumnName].ToString();
if (val != "")
finalValue = finalValue + Convert.ToInt16(val);
dtFinalrows[0][col.ColumnName] = finalValue;
}
else
{
DataRow finalDr = dtFinal.NewRow();
finalDr[col.ColumnName] = finalValue;
finalDr["Agent"] = str;
dtFinal.Rows.Add(finalDr);
}
}
}
}
}
else if (rows.Length == 1)
{
DataRow finalDr = dtFinal.NewRow();
foreach (DataColumn col in dt.Columns)
{
finalDr[col.ColumnName] = rows[0][col.ColumnName];
}
dtFinal.Rows.Add(finalDr);
}