[英]linq-to-sql null or default
我有一個查詢,看起來像這樣:
var TheQuery = (from....
where x.TheDate >= StartDate && x.TheDate <= EndDate
select new MyModel()
{
Total = (int?)x.Count() ?? 0,
....
}).Single();
基本上,我要查詢兩個日期之間的許多記錄。 如果該日期有0個值,則返回0作為總計。 但是,如果根本沒有任何值,它將返回null並崩潰。 我可以添加.SingleOrDefault()
但它將返回null而不是填充為0的MyModel。屬性Total定義為int。
我該如何解決?
謝謝
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
}
要么
var v = TheQuery.ToList();
現在檢查
if (v.Count > 0)
您應該選擇:
int count = (from x in ...
where x.TheDate >= StartDate && x.TheDate <= EndDate
select c).Count();
那正是你想要的。
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.