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

前端 未结 15 2170
礼貌的吻别
礼貌的吻别 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 06:44

    This is a sample I used for my unit test. I created a list of class object. Then I used forloop to add 'X' number of objects that I am expecting from the service. This way you can add/initialize a List for any given size.

    public void TestMethod1()
        {
            var expected = new List();
            for (int i = 0; i < 22; i++)//You add empty initialization here
            {
                var temp = new DotaViewer.Interface.DotaHero();
                expected.Add(temp);
            }
            var nw = new DotaHeroCsvService();
            var items = nw.GetHero();
    
            CollectionAssert.AreEqual(expected,items);
    
    
        }
    

    Hope I was of help to you guys.

提交回复
热议问题