2012-08-14 53 views
1

我有一个文本字符串,项目之间用分号分隔。可能有一个,一对或几百个这些项目。处理来自列表或数组的项目

我需要处理这些项目批量达到100.我可以使用数组或列表,要么罚款。但是,LINQ不是一种选择。

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

+2

问题是什么? – user854301 2012-08-14 20:24:27

+3

你如何定义** process **? – 2012-08-14 20:25:54

+1

你能提供一个你觉得太“笨重”的方法吗? – Servy 2012-08-14 20:28:19

回答

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); 
+0

'Batch'看起来像一个扩展方法。他们是在C#3.0中引入的。 OP使用C#2.0。 – 2012-08-14 20:34:28

+0

@DarinDimitrov:更正。看一看。 – 2012-08-14 20:35:54

0

你甚至不希望超过100的这些存储在内存中的时候,你也可以遍历第100匹配使用String.Split

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]; 
    } 
}; 

我确定有方法来优化这个,但基本思想 - t o使用Splitcount功能来避免与他们一起工作 - 可能是解决问题的最佳方法。

相关问题