繁体   English   中英

在C#中动态创建Collection

[英]Creating Collection dynamically in C#

我有一个应用程序,它将不断获取用户输入并将输入存储在class ItemsValueList

我将如何做到这一点,以便一旦集合达到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.

我不知道为什么,但是您想要一个“列表列表”: 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>());

我认为您需要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);
}

我不知道您的其余代码看起来如何,但是我会让该计数器变为静态。

使用集合列表。 如果大小固定,则可以使用数组而不是列表。

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM