2012-08-14 31 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功能來避免與他們一起工作 - 可能是解決問題的最佳方法。