1

如果我有以下查询:-

var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
            group data by new
            {
                InvNo = data.Field<double>("InvoiceNo"),
                AccRef = data.Field<double>("SiteRefNum"),
            }
            into g
            select new
            {
                Code = "1",
                InvType = "I",
                Account = g.Key.AccRef,
                InvNo = g.Key.InvNo,
                ChargeTotal = g.Sum(d => d.field<double>("Charge")
            };

...排除 ChargeTotal 列总和为零的行的最佳方法是什么?我假设我必须使用 a WHERE,但我不确定在哪里放置它。

4

1 回答 1

5

您没有很多解决方案,因为where必须在group by(取决于组)之后调用,然后:

var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
             group data by new
             {
                 InvNo = data.Field<double>("InvoiceNo"),
                 AccRef = data.Field<double>("SiteRefNum"),
             }
             into g
             let sum = g.Sum(d => d.field<double>("Charge"))  // Sum only computed once
             where sum != 0
             select new
             {
                 Code = "1",
                 InvType = "I",
                 Account = g.Key.AccRef,
                 InvNo = g.Key.InvNo,
                 ChargeTotal = sum
             };

为了稍微提高性能(您必须测试两者以查看是否有任何性能改进,因为它高度依赖于数据),如果 d.field("Charge") 始终 >= 0,您可以执行以下操作:

var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
             group data by new
             {
                 InvNo = data.Field<double>("InvoiceNo"),
                 AccRef = data.Field<double>("SiteRefNum"),
             }
             into g
             where g.Any(d => d.field<double>("Charge") != 0)  
             select new
             {
                 Code = "1",
                 InvType = "I",
                 Account = g.Key.AccRef,
                 InvNo = g.Key.InvNo,
                 ChargeTotal = g.Sum(d => d.field<double>("Charge"))
             };
于 2013-01-29T14:45:49.657 回答