将两个数据集合并到datagridview

时间:2018-01-02 03:50:32

标签: c# .net winforms datagridview dataset

我有两个数据集,我想将它们组合成4列。

dsResult - 显示月份,新卡数量和新卡总数 dsResult2 - 显示月份和充值值。

这是当前的代码:

   DataSet dsResult = objWSX.SelectNewCardSummary(AYear, 
   optCurrency.SelectedValue.ToString());
   DataSet dsResult2 = objWSX.SelectTopupSummary(AYear, 
   optCurrency.SelectedValue.ToString());

   dsResult.Merge(dsResult2);


        if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
        {

            foreach (DataRow dtRow in dsResult.Tables[0].Rows)
            {
                dgvReport.Rows.Add(
                   dtRow["MonthName"].ToString(),
                   dtRow["new_card_qty"].ToString(),
                   dtRow["new_card_total"].ToString(),
                   dtRow["Top_Up_Value"].ToString()

                );
            }

Current output as displayed here:

我希望输出不会有几个月的冗余,并且在datagridview中正确填充。

1 个答案:

答案 0 :(得分:1)

您需要在Enumerable列上将Month转换为DataTable集合和分组,然后从中导出新 if (dsResult != null && dsResult.Tables[0].Rows.Count > 0) { var distinctDataTable = dsResult.Tables[0].AsEnumerable() .GroupBy(row => row.Field<string>("MonthName")) .Select(group => new { MonthName = group.Key, new_card_qty = group.Sum(e => Convert.ToDouble(e["new_card_qty"] == DBNull.Value ? 0 : e["new_card_qty"])), new_card_total = group.Sum(e => Convert.ToDouble(e["new_card_total"] == DBNull.Value ? 0 : e["new_card_total"])), Top_Up_Value = group.Sum(e => Convert.ToDouble(e["Top_Up_Value"] == DBNull.Value ? 0 : e["Top_Up_Value"])), }); foreach (var dtRow in distinctDataTable) { dgvReport.Rows.Add( dtRow.MonthName, dtRow.new_card_qty, dtRow.new_card_total, dtRow.Top_Up_Value, ); } }

Collection