Search code examples
c#ienumerablewebmethodyield

Returning paged results from WebMethod?


I need to create WebMethod that will get some data from db and return that to the client.

Now, assume that the amount of data is huge, so I'd like to take and return data in parts.

Is there any way to use yield return in Webmethod?

As I know there is no way to return generic types in WebMethods, but I couldn't use non-generic IEnumerable as well.

How can I accomplish that?


Solution

  • No, you can't yield return from a WebMethod. But you can add two parameters to the method call to allow paged results:

    public string[] GetResults(string someQuery)
    {
        var results = new List<string>();
    
        // Fill Results
    
        return results.ToArray();
    }
    

    Becomes:

    public string[] GetResults(string someQuery, int pageNum, int pageSize)
    {
        var results = new List<string>();
    
        // Fill Results
    
        return results.Skip(pageNum * pageSize).Take(pageSize).ToArray();
    }