c# - 使用 LINQ 计算特定列的总和

标签 c# linq

使用下面提到的查询,我得到了名为 促销值(value) 。我想得到 *matched *

的所有值的总和
var matched = from table1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
              join table2 in dvPropertyRooms.ToTable().AsEnumerable() on
              table1.Field<DateTime>("RateDate") equals table2.Field<DateTime>("RateDate")
            where table1.Field<DateTime>("RateDate") == table2.Field<DateTime>("RateDate")
               select table1.Field<string>("promotionValue");

最佳答案

您需要parse intdecimal 的字符串:

var matched = from r1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
              join r2 in dvPropertyRooms.ToTable().AsEnumerable() 
              on r1.Field<DateTime>("RateDate").Date equals r2.Field<DateTime>("RateDate").Date
              select decimal.Parse(r1.Field<string>("promotionValue"));
decimal sum = matched.Sum();

请注意,我还更改了一些其他内容,例如多余的 where(因为您已经加入了这些表)或 DateTime 的 Date 属性

除此之外

  1. 您为什么需要 DataViewToTable始终创建一个新的 DataTable。为什么不对所有人使用 Linq-To-DataSet?我假设您已使用 DataView 进行过滤,请改用 Enumerable.Where。这将更一致、更高效且更具可读性。
  2. 为什么 promotionValue 列是一个字符串?您应该将其存储为数字类型。

关于c# - 使用 LINQ 计算特定列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499976/

相关文章:

c# - SQLite:设计数据库并使用自动增量 ID 访问其数据的正确方法?

c# - 如何在运行时从文本构建 LINQ 查询?

c# - 为什么 Bool 数据类型的大小在 C# 中不是只有 1 位?

c# - Predicatebuilder group and or queries with inner outer

c# - 通过 LINQ 查询使用包含

c# - 是否可以使用 linq 枚举两个 IEnumerables 的所有排列

vb.net - Where().Count() 与 Count()

sql-server - 如何编写 EF.Functions 扩展方法?

c# - xsd.exe 为 XML 序列化生成奇怪的 C# 类

c# - 我无法在 visual studio 2010 中将#region 添加到 .ashx