检查linq中的空值

时间:2017-03-04 14:01:40

标签: c# linq

如何在linq查询中检查null ??

这是代码:

 var query = _orderRepository.Table;
        query = query.Where(o => o.AccountId == accountId);
        var result = from d in query
                     where d.CreatedOnUtc != null
                     select d;


        if (result != null)
        {


        }
        //var MinDate = from d in query
        //              where (d.CreatedOnUtc == null ? d.CreatedOnUtc == null : d.CreatedOnUtc == (from d1 in query select d1.CreatedOnUtc).Min())
        //            select d.CreatedOnUtc;
        //var MaxDate = from d in query
        //              where (d.CreatedOnUtc == null ? d.CreatedOnUtc == null : d.CreatedOnUtc == (from d1 in query select d1.CreatedOnUtc).Max())
        //              select d.CreatedOnUtc;

        var rateSum = (query.Sum(d => d.OrderSubtotal));
        var MinDate = (from d in query select d.CreatedOnUtc).Min();
        var MaxDate = (from d in query select d.CreatedOnUtc).Max();
        decimal qry;
        //query = query.Where(c =>
        //((DbFunctions.DiffDays(MinDate, MaxDate) == 0) ? rateSum : (DbFunctions.DiffDays(MinDate, MaxDate) / 30 == 0) ? "rateSum" ? "(rateSum / (DbFunctions.DiffDays(MinDate, MaxDate) / 30)"));
        if ((DbFunctions.DiffDays(Convert.ToDateTime(MinDate), Convert.ToDateTime(MaxDate)) == 0))
            //if ((SqlFunctions.DateDiff("", Convert.ToDateTime(MinDate), Convert.ToDateTime(MaxDate)) == 0))
            {
            qry = (rateSum);
        }
        else if ((DbFunctions.DiffDays(Convert.ToDateTime(MinDate), Convert.ToDateTime(MaxDate)) / 30 == 0))
        {
            qry = (rateSum);

        }
        else
        {
            qry = Convert.ToDecimal(rateSum / (DbFunctions.DiffDays(MinDate, MaxDate) / 30));
        }

        var orderCount = qry;
        return orderCount;

任何人都可以指导我如何在查询值为空时在rateSum,MinDate和MaxDate中检查null。???

我正在努力,但没有工作,所以任何建议???

2 个答案:

答案 0 :(得分:0)

这将允许rateSum为可为空的十进制 我在外连接查询中特别使用它来避免丑陋的the cast to value type failed...异常。

var rateSum = (query.Sum(d => (decimal?)d.OrderSubtotal));

然后你可以检查rateSum为null

当我需要检查查询是否为空时,我使用query.Count()

为了能够检查MinDate是否为null,只需应用相同的系统:

var MinDate = (from d in query select (DateTime?)d.CreatedOnUtc).Min();

答案 1 :(得分:0)

以下方法不适合您

    var rateSum = query.Where(d=>d.OrderSubtotal !=null).Sum(d => d.OrderSubtotal);

PS:您需要将OrderSubtotal更改为十进制吗? (可以为十进制)如果值在DB

中可以为空

和MinDate如下

    var MinDate = query.Where(d=>d.CreatedOnUtc !=null).Min(d =>d.CreatedOnUtc);