简体   繁体   English

linq-to-sql null或默认值

[英]linq-to-sql null or default

I have a query that looks like this: 我有一个查询,看起来像这样:

var TheQuery = (from....
               where x.TheDate >= StartDate && x.TheDate <= EndDate
               select new MyModel()
               {
                   Total = (int?)x.Count() ?? 0,
                   ....
               }).Single();

Basically, I'm querying a number of records based between 2 dates. 基本上,我要查询两个日期之间的许多记录。 If for the date there are 0 values, it returns 0 as the Total. 如果该日期有0个值,则返回0作为总计。 However, if there are no values at all, it returns null and crashes. 但是,如果根本没有任何值,它将返回null并崩溃。 I could add .SingleOrDefault() but it would return null instead of MyModel populated with a 0. The property Total is defined as an int. 我可以添加.SingleOrDefault()但它将返回null而不是填充为0的MyModel。属性Total定义为int。

How can I solve this? 我该如何解决?

Thanks 谢谢

Count has an overload with a predicate, and returns 0 when no item matches the predicate Count具有谓词的重载,并且当没有项目与谓词匹配时返回0

 var result = new MyModel {
                          Total = <yourDataSource>
                            .Count(x.TheDate >= StartDate && x.TheDate <= EndDate)
                          };
if(TheQuery !=null || TheQuery .Count()>0){
 //do something you wanna do

} }

or 要么

 var v = TheQuery.ToList();

now check 现在检查

if (v.Count > 0)

You should opt for: 您应该选择:

int count = (from x in ...
where x.TheDate >= StartDate && x.TheDate <= EndDate
select c).Count();

That's what you want. 那正是你想要的。

var TheQuery = (from....
               where x.TheDate >= StartDate && x.TheDate <= EndDate
               select new MyModel()
               {
                   Total = (int?)x.Count() ?? 0,
                   ....
               }).DefaultIfEmpty(0).Single()'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM