2014-04-24 65 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()稍后。 –