【问题标题】:Creating Collection dynamically in C#在 C# 中动态创建集合
【发布时间】:2014-04-24 15:53:06
【问题描述】:

我有一个应用程序,它会不断地接受用户的输入并将输入存储在Listclass ItemsValue

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

【问题讨论】:

  • 您可以制作收藏列表。但最初的目的是什么?
  • 为什么?为什么不直接添加到同一个集合中?
  • 为什么不直接使用 Take and Skip?
  • 不,我们需要将数据临时存储在列表中,然后将数据传输到下一个应用程序中。

标签: c#


【解决方案1】:

我不知道为什么,但你想要一个“列表列表”:List&lt;List&lt;ItemsValue&gt;&gt;

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

【讨论】:

  • 看起来我们都同时回答了!你的似乎最简洁,所以你得到我的投票。
  • 是的,但是您的代码和@Selman22 的代码是唯一不会引发异常的代码。 +1 秒
【解决方案2】:

我觉得你需要List&lt;List&lt;ItemsValue&gt;&gt;

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

我不知道你的其余代码是什么样子的,但我会让 counter 成为静态的。

【讨论】:

    【解决方案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);
    }
    

    【讨论】:

    • 您可以将 if 语句的主体压缩为 collections.Add(new List()) 而不会失去任何真正的可读性。
    • 不是为了可读性,更多是为了用新的List来做事。
    • 啊,我明白了。虽然您可以通过稍后简单地执行 collections.Last() 轻松获得该新列表。
    • 是的..这两种方法都没有错..干杯:)
    • 感谢 collections[collections.Count - 1] &gt;= 1000 中的编译器错误,感谢无可辩驳的 IndexOutOfBoundsException 如果代码实际编译并感谢支持者的热情。这与个人无关:问题和其他 N-1 个答案也是如此。
    【解决方案4】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      相关资源
      最近更新 更多