【问题标题】:Trying to set the capacity of list using another variable C# [duplicate]尝试使用另一个变量 C# 设置列表的容量 [重复]
【发布时间】:2021-02-11 23:56:01
【问题描述】:

首先,我对编码很陌生,所以如果这很简单,我很抱歉,我正在尝试编写一个程序,从输入数据中计算每行元音的数量,然后显示每行的计数。我在尝试设置将存储总计数的列表的初始容量时遇到了一个问题,即使 letter.Count = 15,容量也会保持为零。以下是我所拥有的,谢谢你的任何以及所有反馈:

var letters = new List<string>();
        var vowels = new char[] { 'a', 'e', 'i', 'o', 'u'};
        string input;
        while (!String.IsNullOrWhiteSpace(input = Console.ReadLine()))
        {
            letters.Add(input);
            if (letters.Count == input.Length)
                break;
        }

        var length = letters.Count;
        var total = new List<int>(length);

【问题讨论】:

标签: c# list


【解决方案1】:
var total = new List<int>(length);

不分配大小长度的列表,它只是为它保留空间,列表仍然是空的。

根据文档https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=net-5.0#System_Collections_Generic_List_1__ctor_System_Int32_

您可以将项目添加到列表中,但在这种情况下,更好的选择是使用数组,因为它被设计为初始化为固定大小。

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 2018-11-23
    • 2019-05-08
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多