0

什么是Execute批量调用该方法的好方法rulesObjs?假设该列表有超过 10,000 个对象,我想一次调用Execute不超过 500 个。

    public static List<object> ExecutePolicy()
    {
        Policy policy = new Policy();

        List<object> rules = GetRules();

        object[] rulesObjs = rules.ToArray();

        // Call this method with array of object, but in batches.
        policy.Execute(rulesObjs);

        return rulesObjs.ToList();
    }

    private static List<object> GetRules()
    {
        // get the rules via some process
        return new List<object>();
    }
}

public sealed class Policy
{
    public void Execute(params object[] rules)
    {
        // Process rules...
    }
}

我无法控制Execute()方法。

4

3 回答 3

6
List<object> rules = GetRules();
int batchSize = 500;
int currentBatch = 0;

while (currentBatch * batchSize < rules.Count)
{
    object[] nextBatch = rules.Skip(currentBatch * batchSize)
        .Take(batchSize).ToArray();
    //use batch
    currentBatch++;
}
于 2012-09-24T17:06:36.707 回答
2

好吧,如果您可以控制该Execute()方法,那么最好的方法是将索引传递给该方法,以便它知道从数组的哪个索引开始。

public void Execute(int startIndex, /*optional*/ int endIndex, params object[] rules)
{
    // Process rules...
}

不要担心一次传递太多数据。在幕后,你的数组只是一个指针,所以你只是传递一个引用。


如果您无法控制该Execute()方法,则可以使用Array.Copy为您的部分创建一个新数组,并处理该新数组。

于 2012-09-24T17:05:07.510 回答
2

参考System.Linq您可以使用跳过和采取:

int total = 10000;
int chunkSize = 500;
for (int i = 0; i < total; i += chunkSize )
{
    var chunk = rulesObjs.Skip(i).Take(chunkSize).ToArray();

    policy.Execute(chunk);
}
于 2012-09-24T17:09:44.680 回答