List批量赋值的几种方法

时间:2021-02-15 22:18:19

List<int> list = new List<int>();
list.AddRange(new int[] { 1, 5, 10, 20 ,33 });

//也可直接赋值

List<int> list2 = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

//对复杂成员的批量赋值

// 如果容器存放的是非简单对象
            List<Point> pointList = new List<Point>
            {
                new Point { X = 2, Y = 2},
                new Point { X = 3, Y = 3}
            };

// 使用恰当的缩进和嵌套的大括号会使代码易于阅读,同时节省我们的输入时间
            // 想想如果不使用初始化语法构造如下的List,将需要多少行代码
            List<Rectangle> rectList = new List<Rectangle>
            {
                new Rectangle { TopLeft = new Point { X = 1, Y = 1},
                    BottomRight = new Point { X = 2, Y = 2}},
                new Rectangle { TopLeft = new Point { X = 3, Y = 3},
                    BottomRight = new Point { X = 4, Y = 4}},
                new Rectangle { TopLeft = new Point { X = 5, Y = 5},
                    BottomRight = new Point { X = 6, Y = 6}}
            };