在数据表上使用linq并将结果放回到具有相同格式的数据表中

时间:2015-04-01 14:07:27

标签: c# linq datatable

我想做的事情相对简单。我想使用linq来计算组上的一些聚合函数,然后将结果放回到相同格式的数据表中。我做了很多研究,并认为我应该使用System.Data.DataSetExtensions并复制到datatable功能。这是我的随机数据表:

DataTable ADataTable = new DataTable("ADataTable");

        // Fake table data
        ADataTable.Columns.Add("PLANT", typeof(int));
        ADataTable.Columns.Add("PDCATYPE_NAME", typeof(int));
        ADataTable.Columns.Add("Month", typeof(int));
        ADataTable.Columns.Add("Year", typeof(int));
        ADataTable.Columns.Add("STATUS_NAME_REPORT", typeof(string));
        ADataTable.Columns.Add("SAVINGS_PER_MONTH", typeof(double));

        for (int i = 0; i < 15; i++)
        {
            for (int j = 1; j < 5; j++)
            {
                DataRow row = ADataTable.NewRow();

                row["PLANT"] = j;
                row["PDCATYPE_NAME"] = j;
                row["Month"] = DateTime.Now.Month;
                row["Year"] = DateTime.Now.Year;
                row["STATUS_NAME_REPORT"] = "Report";
                row["SAVINGS_PER_MONTH"] = j*i;

                ADataTable.Rows.Add(row);
            }
        }

现在我将克隆这种格式,并通过linq:

对其进行简单的总结
 DataTable newtable = ADataTable.Clone();

        // The actual query
        IEnumerable<DataRow> query = (from rows in ADataTable.AsEnumerable()
                                      group rows by new
                                      {
                                          PLANT = rows.Field<int>("PLANT"),
                                          PDCATYPE_NAME = rows.Field<int>("PDCATYPE_NAME"),
                                          Month = rows.Field<int>("Month"),
                                          Year = rows.Field<int>("Year"),
                                          STATUS_NAME_REPORT = rows.Field<string>("STATUS_NAME_REPORT")
                                      } into g

                                      select new  
                                      {
                                           g.Key.PLANT,
                                           g.Key.PDCATYPE_NAME,
                                          g.Key.Month,
                                          g.Key.Year,
                                          g.Key.STATUS_NAME_REPORT,
                                          sum = g.Sum(savings => savings.Field<double>("SAVINGS_PER_MONTH")),
                                      });

        newtable = query.CopyToDataTable<DataRow>();

LINQ工作正常但是只要我把IEnumarable DataRow放在前面我就会收到错误,我无法将anonymys类型转换为datarow。但是如果我把select new datarow我得到一个错误,那就是字段未知......

我该如何处理?

2 个答案:

答案 0 :(得分:2)

您有多种选择,首先是use reflection to create DataTable基于IEnumerable<T>,其他选项是通过枚举您的查询来填充您的DataTable

var query = ADataTable.AsEnumerable()
    .GroupBy(row => new
    {
        PLANT = row.Field<int>("PLANT"),
        PDCATYPE_NAME = row.Field<int>("PDCATYPE_NAME"),
        Month = row.Field<int>("Month"),
        Year = row.Field<int>("Year"),
        STATUS_NAME_REPORT = row.Field<string>("STATUS_NAME_REPORT")
    });

foreach (var g in query)
{
    newtable.LoadDataRow(new object[]
    {
                 g.Key.PLANT,
                 g.Key.PDCATYPE_NAME,
                 g.Key.Month,
                 g.Key.Year,
                 g.Key.STATUS_NAME_REPORT,
                g.Sum(savings => savings.Field<double>("SAVINGS_PER_MONTH"))
    }, LoadOption.OverwriteChanges);
}

代码中的错误是因为使用select new选择匿名类型,然后尝试将其存储在IEnumerable<DataRow>中。您无法在DataRow中指定select,因为它无法直接访问。

您可能还会看到:How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

答案 1 :(得分:1)

这也有效:

newtable2 = ADataTable.AsEnumerable().GroupBy(a => new
{
    PLANT = a.Field<int>("PLANT"),
    PDCATYPE_NAME = a.Field<int>("PDCATYPE_NAME"),
    Month = a.Field<int>("Month"),
    Year = a.Field<int>("Year"),
    STATUS_NAME_REPORT = a.Field<string>("STATUS_NAME_REPORT")
}).Select(g =>
{
    var row = newtable2.NewRow();
    row.ItemArray = new object[]
            {
                g.Key.PLANT, 
                g.Key.PDCATYPE_NAME,
                g.Key.Month,
                g.Key.Year,
                g.Key.STATUS_NAME_REPORT,
                g.Sum(r => r.Field<double>("SAVINGS_PER_MONTH"))
            };
    return row;
}).CopyToDataTable();

使用System.Data.DataSetExtensions(需要引用)