循环遍历datagridview和相同id的总量

时间:2017-01-19 05:42:31

标签: c# datagridview

我想在每个日期获取每个ID的总金额。

示例数据:

:setvar path "Variable"
PRINT '$(path)'

这都是在datagridview中并且有很多行。对于“2017-01-03”中的“619”,我有3种不同的金额,例如418.80,497.48和29.13。我想总计这个金额并将其放在最后一个条目下面,如下所示。

ID                  Date        Amount
619|RENE ABERIA     2017-01-03  418.80
619|RENE ABERIA     2017-01-03  497.48
619|RENE ABERIA     2017-01-03  29.13
620|JAMES APRECIO   2017-01-03  460.70
620|JAMES APRECIO   2017-01-03  76.33
620|JAMES APRECIO   2017-01-04  460.70
620|JAMES APRECIO   2017-01-04  59.32
620|JAMES APRECIO   2017-01-06  460.70

我想我必须使用FOR LOOP去每一行,但我不知道如何去做或继续。以下是我到目前为止的情况,显然,完成它还有很长的路要走。

ID                  Date        Amount
619|RENE ABERIA     2017-01-03  418.80
619|RENE ABERIA     2017-01-03  497.48
619|RENE ABERIA     2017-01-03  29.13
                    Total:      945.41
620|JAMES APRECIO   2017-01-03  460.70
620|JAMES APRECIO   2017-01-03  76.33
                    Total:      537.03
620|JAMES APRECIO   2017-01-04  460.70
620|JAMES APRECIO   2017-01-04  59.32
                    Total:      520.02
620|JAMES APRECIO   2017-01-06  460.70
                    Total:      460.70

这与“how I can show the sum of in a datagridview column?”中的问题不同,因为该示例仅对该列中的所有内容进行求和。我需要的是将具有相同ID和相同日期的列的值相加。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

将信息收集到字典中后,循环遍历数据。

现在字典将包含每个ID和日期的数字列表,可以轻松计算。

private void GetTotalShareForDay()
{
    var results = new Dictionary<Tuple<string, string>,List<decimal>>();

    for (var i = 0; i < dgvSummary.Rows.Count; i++)
    {
        string laborerId = dgvSummary.Rows[i].Cells[0].Value.ToString();
        string date = dgvSummary.Rows[i].Cells[1].Value.ToString();

        Tuple<string, string> uniqueKey = new Tuple<string, string>(laborerID, date); // laborerID and date combined provide uniqueness

        decimal share = Convert.ToDecimal(dgvSummary.Rows[i].Cells[5].Value);

        if (!results.ContainsKey(uniqueKey)) 
            results.Add(uniqueKey, new List<double>());
        results[uniqueKey].Add(share);
    }

    foreach(var key in results.Keys)
    {
        // key.Item1 is laborerID
        // key.Item2 is Date as string
        decimal sum = results[key].Sum();
        Console.Write("Laborer ID:" + key.Item1);
        Console.Write("Date:" + key.Item2);
        Console.Write("Sum:" + sum);
    }
}

带有元组的版本(首选)

$('.arrow-up').on('click', function() {
  // select `i` tag with class `fa` withtin the div and toggle both classes
  $('i.fa', this).toggleClass('fa-chevron-up fa-chevron-down');
});
相关问题