How can I get a sum for the column “pieces” in a datatable?

纵然是瞬间 提交于 2019-12-03 04:03:38

Using the DataTable.Compute method, you can do:

int sum = (int)table.Compute("Sum(pieces)", "article = 'milk' AND artno='15'");

You could use the AsEnumerable method like so:

var results = dataTable.AsEnumerable()
                       .Where(row => row.Field<string>("article") == "milk" && 
                                     row.Field<int>("artno") == 15)
                       .Select(row => row.Field<int>("pieces"))
                       .Sum();

Using Michael's suggestion with 1 less step:

var results = dataTable.AsEnumerable()
                       .Where(row => (row.Field<string>("article ") == "milk") &&
                                     (row.Field<int>("artno") == 15))
                       .Sum(row => row.Field<int>("pieces"));

(This is using Linq to DataSet)

in a .NET 4 windows application, this snippet of code gives 9 in the sum variable:

    DataTable dt = new DataTable("aaa");

    dt.Columns.Add("pieces", typeof(int));

    dt.Rows.Add(new object[] { 1 });
    dt.Rows.Add(new object[] { 3 });
    dt.Rows.Add(new object[] { 5 });

    var sum = dt.Compute("SUM(pieces)", string.Empty);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!