2014-04-24 63 views
0

我會不斷記錄用戶輸入的應用程序和輸入存儲在class ItemsValue創建集動態在C#

一個List我怎麼讓它這樣一旦集合達到1000次,它會「停止「,並創建一個新的集合,等等。

例如:

List<ItemsValue> collection1 = new List<ItemsValue>(); 
//User input will be stored in `collection1` 
if (collection1.count >= 1000) 
    //Create a new List<ItemsVales> collection2, 
    //and the user input will be stored in collection2 now. 
    //And then if collection2.count reaches 1000, it will create collection3. 
    //collection3.count reaches 1000, create collection4 and so on. 
+2

您可以製作收藏列表。但最初的目的是什麼? –

+1

爲什麼?爲什麼不只是添加到相同的集合? – Euphoric

+7

[XY問題?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Liam

回答

3

我想你需要List<List<ItemsValue>>

List<List<ItemsValue>> mainCollection = new List<List<ItemsValue>>(); 
int counter = 0; 
if (counter == 0) mainCollection.Add(new List<ItemsValue>()); 

if(mainCollection[counter].Count < 1000) mainCollection[counter].Add(item); 

else 
{ 
    mainCollection.Add(new List<ItemsValue>()); 
    counter++; 
    mainCollection[counter].Add(item); 
} 

我不知道怎麼是你的代碼看起來和其他人一樣,但我會作出這樣的計數器靜。

4

我不知道爲什麼,但你想要一個「列表清單」:List<List<ItemsValue>>

List<List<ItemsValue>> collections = new List<List<ItemsValue>>(); 
collections.Add(new List<ItemsValue>()); 

collections.Last().Add(/*user input*/); 

if (collections.Last().Count >= 1000) collections.Add(new List<ItemsValue>()); 
+1

看起來我們都在同一個答案時間!你的看法最簡潔,所以你得到我的投票。 –

+1

是的,但是您的代碼和@ Selman22的代碼是唯一不會拋出異常的代碼。 + 1s –

2

試試這個:

List<List<ItemsValue>> collections = new List<List<ItemsValue>>({new List<ItemsValue>()}); 

if(collections[collections.Count-1].Count >= 1000) 
{ 
    collections.Add(new List<ItemsValue>()); 
} 

,當你將項目添加到收藏使用上面的if語句。要將項目添加到系列,請使用以下內容:

collections[collections.Count-1].Add(yourItem); 
3

使用集合列表。如果您有固定大小,則可以使用數組而不是列表。

List<List<ItemsValue>> collections = new List<List<ItemsValue>>({new List<ItemsValue>()}); 
if(collections[collections.Count- 1].Count >= 1000) 
{ 
    var newCollection = new List<ItemsValue>(); 
    // do what you want with newCollection 
    collections.Add(newCollection); 
} 
+0

您可以將if語句的主體濃縮爲collections.Add(新列表()),而不會丟失任何真正的可讀性。 –

+0

這不是爲了便於閱讀,而是爲了處理新列表。 –

+0

啊我明白了。雖然你可以輕鬆地通過簡單地去收藏.Last()稍後。 –