Add entities to and execute "ExecuteMultipleRequest" I have a method which takes a list of Entity objects, loop through elements in that list and add them to a "ExecuteMultipleRequest" object. After that the ExecuteMultipleRequest will be executed.

However, according to Microsoft Dynamic CRM specs, I can only add at most 1000 entities to ExecuteMultipleRequest at one time, or else that request will throw an error when executed, and my list might have more than 1000 elements.

I have come up with the following solution to make sure that at least 1 request will be executed for every 1000 elements, but I find it to be inelegant. What can I improve here?

private readonly int MAXTOBEPROCESSED = 1000;

public void processEntities (List&lt;Entity&gt; entities)
{
    var toBeProcessed = 0;
    var createMultiple = new ExecuteMultipleRequest()
    {
        Settings = new ExecuteMultipleSettings()
        {
            ContinueOnError = false,
            ReturnResponses = true
        },
        Requests = new OrganizationRequestCollection()
    };

    foreach (var entity in entities)
    {
        var createRequest = new CreateRequest{ Target = entity };
        createMultiple.Requests.Add(createRequest);

        if (++toBeProcessed &gt;= MAXTOBEPROCESSED)
        {
            var responseWithResults = (ExecuteMultipleResponse)service.Execute(createMultiple);

            createMultiple = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };
            toBeProcessed = 0;
        }
    }

    if (toBeProcessed != 0)
    {
        var responseWithResults = (ExecuteMultipleResponse)service.Execute(createMultiple);
    }
}
Your logic looks fine to me. If you find yourself creating something in two places then feel free to create a helper function to do so.

Your logic can be arguably simpler if you count down rather than up, since we already know the number of requests.

Something like:

private static int MAXTOBEPROCESSED = 1000;

public void processEntities (List&lt;Entity&gt; entities)
{
    var createMultiple = CreateMultipleRequest();

    for (int n = entities.Count; n &gt; 0; n--)
    {
        createMultiple.Requests.Add(new CreateRequest{ Target = entities[n] });

        if (n % MAXTOBEPROCESSED == 0)
        {
            var responseWithResults = (ExecuteMultipleResponse)service.Execute(createMultiple);
            createMultiple = CreateMultipleRequest();
        }
    }
}

private CreateMultipleRequest()
{
    return new ExecuteMultipleRequest()
    {
        Requests = new OrganizationRequestCollection(),
        Settings = new ExecuteMultipleSettings()
        {
            ContinueOnError = false,
            ReturnResponses = true
        }
    };
}