在linq to sql查询中处理null [英] handling a null in linq to sql query

查看:94
本文介绍了在linq to sql查询中处理null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象:

public class MyObject{

  public int Prop1 {get;set;}
}

我正在执行linq to sql查询,该查询返回的MyObject列表如下:

I'm doing a linq to sql query that returns a list of MyObject like this:

var TheQuery = from ....
               where ....
               select new MyObject()
               {

                 Prop1 = (...... ).Sum( d => d)

               }.ToList();

问题在于Prop1是子查询的总和,有时可能不返回任何内容,并且Sum为null,因为它是一个int,所以无法将其分配给Prop1.

The problem is that Prop1 is a sum of a subquery and sometimes there might be nothing returned and the Sum is null, which can't be assigned to Prop1 because it's an int.

解决这个问题的好方法是什么.

What's a good way around this.

感谢您的建议.

推荐答案

如何使用范围变量:

var TheQuery = from ....
               where ....
               let subquery = (...... )
               select new MyObject()
               {

                 Prop1 = subquery!=null ? (subquery.Sum( d => d) ?? 0) : 0;

               }.ToList();

这篇关于在linq to sql查询中处理null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆