Barry Doyle Barry Doyle - 3 months ago 12
ASP.NET (C#) Question

How to check if LinqDataSource is empty after selecting?

I have an

asp.NET
application where I use a
LinqDataSource
control to fill a
ListView
control. Here's the code for my
LinqDataSource
control's
OnSelecting
command:

protected void lds_Selecting(object sender, LinqDataSourceSelectEvenArgs e)
{
var db = new Models.EF.Entities();
e.Result = from x in db.Sliders
where x.IsPublic == true
select x;
}


This works great but now I want to run an if statement in the case that the result is empty. How can I see if the result is empty?

Answer

Use the Any method. Plus, LinqDataSourceSelectEvenArgs stores the data as an object so cast so use the as to get the IEnumerable<T> on which you can run the Any:

e.Result = (from x in db.Sliders
            where x.IsPublic == true
            select x);

var collection = e.Result as IEnumerable<Slider>;
if(collection != null && !collection.Any()) 
{ 
    /*your code*/
}