2

我正在使用对象类型变量来存储查询结果以绑定到下拉列表。如果是,我不想对对象进行进一步处理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
}

如何检查对象类型变量是否为空/空?

4

4 回答 4

3

您的对象course永远不会为空,它可能包含也可能不包含记录。由于您正在重新获取结果object,因此您应该将其转换为 IEnumerable and useAny` 以查看它是否包含记录。你可以试试:

if ((course as IEnumerable<object>).Any())
{
    //records found
}
{
    //no record found
}
于 2013-04-16T12:14:54.680 回答
2
if (course != null && (course as IEnumerable<object>).Any())
{
}

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

if (course  is IList)
{

}
于 2013-04-16T12:16:43.533 回答
1

查询不为空,而是为空。但是由于您使用的是一个对象,所以您不能使用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

于 2013-04-16T12:18:44.260 回答
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()) ...
于 2013-04-16T12:19:31.260 回答