如何检查对象的空值

时间:2013-04-16 12:09:49

标签: c# asp.net

我正在使用对象类型变量来存储用于绑定到下拉列表的查询结果。如果对象是null,我不希望对该对象进行进一步处理。

我的代码是:

object course;
if (GetWebsiteCurrentMode().ToLower() == "demo")
{
    course = from t in context.CourseTestDetails
            join c in context.Courses
            on t.CourseID equals c.ID                                  
            where t.UserID == UserID && c.IsDeleted == true
            select new
            {
                c.ID,
                c.CourseName
            };

}
else
{
    course = from t in context.CourseTestDetails
            join c in context.Courses
            on t.CourseID equals c.ID                                  
            where t.UserID == UserID  c.IsDeleted == false
            select new
            {
                c.ID,
                c.CourseName
            }
}
if(course !=null )
{
    ddlCourseName.DataSource = course;
    ddlCourseName.DataBind();

    ddlCourseName.Items.Insert(0, new ListItem("Select Course Name", "0"));
    ddlCourseName.SelectedValue = "0";
}
else
{
    //do something different
}

如何检查对象类型变量为null / empty?

4 个答案:

答案 0 :(得分:3)

您的对象course永远不会为空,它可能包含也可能不包含记录。由于您将结果返回到object,因此您应该将其转换为IEnumerable and use Any`以查看它是否包含记录。你可以尝试:

if ((course as IEnumerable<object>).Any())
{
    //records found
}
{
    //no record found
}

答案 1 :(得分:2)

if (course != null && (course as IEnumerable<object>).Any())
{
}

可选:此外,您还应该检查该对象是否实现IList接口

if (course  is IList)
{

}

答案 2 :(得分:1)

查询不是null但是为空。但是,由于您使用的是对象,因此无法使用Enumerable.Empty。您可以使用E. Lippert中的以下技巧为多个IEnumerable<anynymous type>获取一个推断类型的变量:

使用此方法从匿名类型创建类型变量:

static IEnumerable<T> SequenceByExample<T>(T t){ return null; }

现在可行:

var course = SequenceByExample(new { ID = 0, CourseName = "" } );
if (GetWebsiteCurrentMode().ToLower() == "demo")
{
    course = from t in context.CourseTestDetails
            join c in context.Courses
            on t.CourseID equals c.ID                                  
            where t.UserID == UserID && c.IsDeleted == true
            select new
            {
                c.ID,
                c.CourseName
            };
}
else
{
    course = from t in context.CourseTestDetails
    // ...
}
if(course.Any())
{
   // ...
}
else
{
    //do something different
}

Declaring an implicitly typed variable inside conditional scope and using it outside

这是一个简单的例子来证明它有效:http://ideone.com/lDNl4d

答案 3 :(得分:0)

var course = from t in context.CourseTestDetails
                 join c in context.Courses
                 on t.CourseID equals c.ID                                  
                 where t.UserID == UserID && c.IsDeleted == (GetWebsiteCurrentMode().ToLower() == "demo")
                 select new
                 {
                     c.ID,
                     c.CourseName
                  };

if (course.Any()) ...