【问题标题】:Fill List<int> with default values? [duplicate]用默认值填充 List<int>? [复制]
【发布时间】:2010-07-29 15:04:30
【问题描述】:

可能重复:
Auto-Initializing C# Lists

我有一个整数列表,它具有一定的容量,我想在声明时自动填充。

List<int> x = new List<int>(10);

有没有更简单的方法来用 10 个具有默认值的 int 填充这个列表,而不是循环并添加项目?

【问题讨论】:

  • 还有stackoverflow.com/questions/466946/… 和其他一些人。
  • 是的,我的问题是第一个问题的欺骗......
  • 对我来说似乎是重复的,但实际上不是。 并不是所有的程序员都知道java的数组初始化。

标签: c# list


【解决方案1】:

好吧,你可以让 LINQ 为你做循环:

List<int> x = Enumerable.Repeat(value, count).ToList();

不清楚“默认值”是指 0 还是自定义默认值。

您可以通过创建一个数组来稍微提高效率(在执行时间方面;在内存方面更糟):

List<int> x = new List<int>(new int[count]);

这会将数组中的块复制到列表中,这可能比ToList所需的循环更有效。

【讨论】:

  • 我希望有一些可爱的小方法调用来做到这一点,比如'new List(10).Fill()' 或其他东西。感谢您的快速回答。
  • @JonSkeet:自定义班级列表可以吗?例如:List&lt;Items&gt; listOfItems 其中public Items {int id; DateTime currentDateTime;} 需要与currentDateTime 具有相同的值。可能吗?
  • @user1671639:不清楚您要的是什么(也不清楚为什么Items 会是复数而不是Item)。为什么创建一个包含很多这样的“默认”条目的列表会很有用?我建议你问一个更详细的新问题。
  • @JonSkeet:我会问一个新问题。谢谢乔恩。
  • 嘿@JonSkeet,您将如何为 List> 执行上述操作?我已经问过问题here
【解决方案2】:
int defaultValue = 0;
return Enumerable.Repeat(defaultValue, 10).ToList();

【讨论】:

    【解决方案3】:

    如果您有一个固定长度的列表,并且希望所有元素都具有默认值,那么也许您应该只使用数组:

    int[] x  = new int[10];
    

    或者,这可能是自定义扩展方法的好地方:

    public static void Fill<T>(this ICollection<T> lst, int num)
    {
        Fill(lst, default(T), num);
    }
    
    public static void Fill<T>(this ICollection<T> lst, T val, int num)
    {
        lst.Clear();
        for(int i = 0; i < num; i++)
            lst.Add(val);
    }
    

    然后你甚至可以为 List 类添加一个特殊的重载来填满容量:

    public static void Fill<T>(this List<T> lst, T val)
    {
        Fill(lst, val, lst.Capacity);
    }
    public static void Fill<T>(this List<T> lst)
    {
        Fill(lst, default(T), lst.Capacity);
    }
    

    那么你可以说:

    List<int> x  = new List(10).Fill();
    

    【讨论】:

      【解决方案4】:

      是的

      int[] arr = new int[10];
      List<int> list = new List<int>(arr);
      

      【讨论】:

        【解决方案5】:
        var count = 10;
        var list = new List<int>(new int[count]);
        

        添加

        这是获取具有默认值的列表的通用方法:

            public static List<T> GetListFilledWithDefaulValues<T>(int count)
            {
                if (count < 0)
                    throw new ArgumentException("Count of elements cannot be less than zero", "count");
        
                return new List<T>(new T[count]);
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-19
          • 2020-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-28
          • 2021-02-06
          相关资源
          最近更新 更多