处理List或Array中的项目组

时间:2012-08-14 20:22:39

标签: c# .net-2.0

我有一串文字,其中的项目用分号分隔。可能有一个,几个或数百个这些项目。

我需要批量处理这些项目,最多100个。我可以使用数组或列表,也可以。但是,LINQ不是一种选择。

我可以拿出笨重的方法来做到这一点,但有没有办法做到这一点既有效又紧张?

2 个答案:

答案 0 :(得分:2)

使用此

public static IEnumerable<IEnumerable<T>> Batch<T>(IEnumerable<T> collection, 
                                                   int batchSize)
{
    List<T> nextbatch = new List<T>(batchSize);
    foreach (T item in collection)
    {
        nextbatch.Add(item);
        if (nextbatch.Count == batchSize)
        {
            yield return nextbatch;
            nextbatch = new List<T>(batchSize);
        }
    }
    if (nextbatch.Count > 0)
        yield return nextbatch;
}

并使用此

var result = Batch("item1;item2;item3".Split(';'), 100);

答案 1 :(得分:0)

你甚至不希望在内存中一次存储超过100个,你可以使用String.Split循环前100个匹配:

string input; //your string
int i;
string[] inputArray; //tring split on semicolon goes here
while(true)
{
    inputArray = input.Split(new char[]{";"}, 101) //only split on first 101 times
    if (inputArray.Count <= 100) //last iteration
    {
        for (i = 0; i < inputArray.Count; i++)
            SendEmail(inputArray[i]);
        break;
    }
    else //will have left over for another loop
    {
        for (i = 0; i < 100; i++)
            SendEmail(inputArray[i]);
        input = inputArray[100];
    }
};

我确信有一些方法可以对此进行优化,但基本的想法 - 使用count的{​​{1}}功能来避免全部使用它们 - 可能是解决问题的最佳方法