【问题标题】:Does not get exception when collection is empty with Sum method and Nhibernate使用 Sum 方法和 Nhibernate 集合为空时不会出现异常
【发布时间】:2013-04-20 23:39:48
【问题描述】:

我有一个带有 NHibernate 的 IQueryable,我想要一个 linq 查询来对特定列求和,但是,当我在 Where 方法上的条件给我一个空结果时,我不想得到一个异常,但我不想通过查询来获取所有记录,然后在内存中求和后,我想要coalese sql 命令之类的示例:

// I get exception when its empty
var query = MyQueryable()
              .Where(x => x.IsDone)
              .Select(x => x.Value)
              .Sum(); 

我必须这样做:

// I get 0, its ok, but ToList(), list all records on memory, 
// I just want to get a single value

var query = MyQueryable()
               .Where(x => x.IsDone)
               .Select(x => x.Value)
               .ToList()
               .Sum(); 

有什么办法吗?

谢谢。

【问题讨论】:

  • 使用 Any 运算符的 if 条件怎么样?
  • 你试过DefaultIfEmpty吗?
  • NHibernate 的 Linq 不支持DefaultIfEmpty :(

标签: c# linq nhibernate sum iqueryable


【解决方案1】:

您需要将Value 强制转换为可为空的类型。

例如,假设Valueint 属性:

var result = MyQueryable()
                 .Where(x => x.IsDone)
                 .Select(x => (int?)x.Value)
                 .Sum()
             ?? 0;

由于可空枚举上的 Sum() 将为空源返回 null,因此发生这种情况时,合并运算符 (??) 会负责返回 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 2011-06-03
    • 2017-09-18
    相关资源
    最近更新 更多