0

Is it possible to do the below requirement in C# 4.0

Current: I have a data provider class which queries the DB/XML/ExternalDataSource As shown below, the function PerformQuery takes two params and returns a list of type Result.

In my client application the instance of DataProvider call to PerformQuery will create the list and return.

Objective: If the query result of PerformQuery is more (ex. 100K) then the user will have to wait. So I can either create a backgroundworker and the process the list returned by PerformQuery.

But I want to know if the PerformQuery can return each item in its foreach statement to the caller function in sync or async mode. Instead of waiting to build the entire list in the foreach statement and again processing the list in client application.

Caller-->PerformQuery(a,b) ^ | | | | | Send back each result item to the caller function. <---------<

    class DataProvider
    {
       public List PerformQuery(string param1, string param2)
       {
           List m_res = new List();

           var m_queryRes = DataAccessor.GetResults(param1, param2);

           foreach(var res in m_queryRes)
           {    
                  Result result = new Result();
                  result.Name = res.FirstName + res.SecondName;
                  result.Code = res.Code + "Some business logic";
                  m_res.Add(result);              
           }

           return m_res;
       }
    }
    class Result
    {
       Property Name;
       Property Code;
    }

1
  • It should be noted that the significant performance hit will occur when you call DataAccessor.GetResults(). Commented Mar 13, 2012 at 18:11

1 Answer 1

3

You should consider using iterators, with iterators you can return each element at a time based on the request of the caller.

class DataProvider
{
   public System.Collections.IEnumerable<Result> PerformQuery(string param1, string param2)
   {
       var m_queryRes = DataAccessor.GetResults(param1, param2);

       foreach(var res in m_queryRes)
       {    
              Result result = new Result();
              result.Name = res.FirstName + res.SecondName;
              result.Code = res.Code + "Some business logic";
              yield return result;            
       }

   }
}
class Result
{
   Property Name;
   Property Code;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for my delayed response.. Had limited internet access past few days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.