[英]How to check an object for null values
我正在使用对象类型变量来存储查询结果以绑定到下拉列表。 如果对象为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?
您的对象course
永远不会为空,它可能包含记录,也可能不包含记录。 由于要在object
返回结果,因此应将其强制转换为IEnumerable and use
Any`查看其中是否包含记录。 你可以试试:
if ((course as IEnumerable<object>).Any())
{
//records found
}
{
//no record found
}
if (course != null && (course as IEnumerable<object>).Any())
{
}
可选:另外,您还应该检查对象是否实现了IList接口
if (course is IList)
{
}
查询不是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
}
这是一个简单的示例来演示它的工作原理: http : //ideone.com/lDNl4d
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()) ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.