How to initialize a List to a given size (as opposed to capacity)?

前端 未结 15 2168
礼貌的吻别
礼貌的吻别 2020-11-28 06:41

.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization

15条回答
  •  渐次进展
    2020-11-28 07:04

    I can't say I need this very often - could you give more details as to why you want this? I'd probably put it as a static method in a helper class:

    public static class Lists
    {
        public static List RepeatedDefault(int count)
        {
            return Repeated(default(T), count);
        }
    
        public static List Repeated(T value, int count)
        {
            List ret = new List(count);
            ret.AddRange(Enumerable.Repeat(value, count));
            return ret;
        }
    }
    

    You could use Enumerable.Repeat(default(T), count).ToList() but that would be inefficient due to buffer resizing.

    Note that if T is a reference type, it will store count copies of the reference passed for the value parameter - so they will all refer to the same object. That may or may not be what you want, depending on your use case.

    EDIT: As noted in comments, you could make Repeated use a loop to populate the list if you wanted to. That would be slightly faster too. Personally I find the code using Repeat more descriptive, and suspect that in the real world the performance difference would be irrelevant, but your mileage may vary.

提交回复
热议问题