在DataTable上按日期填充行

时间:2018-12-26 06:40:15

标签: c# database linq datatable row

我有一个DataTable和这样的行:

--------------------------------------------
|   date   |   a   |   b   |   c   |   d   |
--------------------------------------------
|     x    |  200  |  30   |   5   |   7   |
--------------------------------------------

这段代码将过去到现在的每个数字加起来:

var topla = Dao.Sum<x>(a => (a.Orj_Fiyat_VergiDahil * a.Ana_Miktar * a.Kur) - a.Iskonto_Tutar, a => (urunidler.Contains(a.Urun_Id)));

A,b,c和d是每个项目的类别。并向我们​​显示了他们从第一个销售到最后一个销售的销售。因此,从开始到今天,我售出200美元的“ a”商品。但我想像这样填充此数据表:

--------------------------------------------
|   date   |   a   |   b   |   c   |   d   |
--------------------------------------------
| 24.12.18 |  100  |  10   |   2   |   1   |
--------------------------------------------
| 25.12.18 |  50   |  5    |   1   |   1   |
--------------------------------------------
| 26.12.18 |  1    |  3    |   2   |   1   |
--------------------------------------------

(数字为示例)

我该怎么做?谁能帮我吗?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable Dao = new DataTable();

            var groups = Dao.AsEnumerable().GroupBy(x => x.Field<DateTime>("date").Date).ToList();

            DataTable sumTable = Dao.Clone();
            int numberOfColumns = sumTable.Columns.Count;

            foreach (var group in groups)
            {
                DataRow newRow = sumTable.Rows.Add();
                newRow["date"] = group.Key;

                for (int col = 1; col < numberOfColumns; col++)
                {
                    newRow[col] = group.Sum(x => (int)x[col]);
                }
            }
        }
    }
}