开发者

What does an Empty IQueryable return as when Empty?

I am in need of determining whether an IQueryable Method returns with Data, or "Empty" when applying it to a DataSource of a RadGrid like so:

RadGrid.DataSource = Method(x);

        if (Method(x) == yyy)
        {
            button.Enabled = true;
        }
        else
        {
            button.Enabled = false;
        }

I have tried using "null" in place of the "yyy" but with no开发者_高级运维 success. When stepping through the code, the IQueryable Method returns as "Empty" but I am unsure of how to verify that using an If statement.

What does an IQueryable Method return as if it returns as Empty, and how can I verify that using an If Statement?


You can use Any() to check to see if there are any elements in the IQueryable:

RadGrid.DataSource = Method(x);

if (Method(x).Any())
{
    button.Enabled = true;
}
else
{
    button.Enabled = false;
}

(Or, alternatively, the shorter version:)

button.Enabled = Method(x).Any();


You want to use IQueryable.Any.

bool empty = !queryable.Any();
if(empty) {
    // something
}


Try something like

RadGrid.DataSource = Method(x);            
 if (RadGrid.DataSource as MyObject == null)          
 {              
      button.Enabled = true;          
 }          
 else          
 {              
       button.Enabled = false;          
 }  


Try this:

if (Method(x) == Enumerable.Empty<YourType>())
{
    // Your code
}

Since Enumerable.Empty<TResult>() is cached for TResult it will hold the same reference as the empty sequence reterned from Method and therefore will be equatable.

If you are unsure whether or not this will work, please run this example:

using System;
using System.Linq;

class Example
{
    static void Main()
    {
        var first = Enumerable.Empty<Example>();
        var second = Enumerable.Empty<Example>();

        Console.WriteLine(object.ReferenceEquals(first, second));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜