简体   繁体   English

在C#中动态创建Collection

[英]Creating Collection dynamically in C#

I have an application that will continuously taking user's input and store the input in a List of class ItemsValue 我有一个应用程序,它将不断获取用户输入并将输入存储在class ItemsValueList

How am I going to make it so that once the collection reaches 1000 counts, it will "stop" and a new collection will be created and so on. 我将如何做到这一点,以便一旦集合达到1000个计数,它将“停止”并创建一个新的集合,依此类推。

For example: 例如:

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.

I don't know why, but you want a "list of lists": List<List<ItemsValue>> . 我不知道为什么,但是您想要一个“列表列表”: 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>());

I think you need List<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);
}

I don't know how is the rest of your code look like,but I would make that counter static. 我不知道您的其余代码看起来如何,但是我会让该计数器变为静态。

Use a list of collections. 使用集合列表。 If you have fixed size you can use a array instead of a list. 如果大小固定,则可以使用数组而不是列表。

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

Try this: 尝试这个:

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

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

Use the above if statement when you're adding an item to collections. 将项目添加到集合时,请使用上述if语句。 To add an item to collections, use the following: 要将项目添加到集合中,请使用以下命令:

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

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

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