c# List AddRange

https://msdn.microsoft.com/zh-cn/library/z883w3dc(v=vs.80).aspx

 

List 中会保留集合中元素的顺序。

如果新的 Count(当前 Count 加上集合的大小)大于 Capacity,则会通过自动重新分配内部数组增大 List 的容量以容纳新元素,并在添加新元素之前将现有元素复制到新数组中。

如果 List 可以在不增加 Capacity 的情况下容纳新元素,则此方法是 O(n) 运算,其中 n 是要添加的元素数。如果需要增加此容量以容纳新元素,则此方法变为 O(n + m) 运算,其中 n 是要添加的元素数,m 是 Count

 

List.AddRange :将指定集合的元素添加到 List 的末尾。

 

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] input = { "Brachiosaurus", 
                           "Amargasaurus", 
                           "Mamenchisaurus" };

        List<string> dinosaurs = new List<string>(input);

        Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nAddRange(dinosaurs)");
        dinosaurs.AddRange(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nRemoveRange(2, 2)");
        dinosaurs.RemoveRange(2, 2);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        input = new string[] { "Tyrannosaurus", 
                               "Deinonychus", 
                               "Velociraptor"};

        Console.WriteLine("\nInsertRange(3, input)");
        dinosaurs.InsertRange(3, input);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\noutput = dinosaurs.GetRange(2, 3).ToArray()");
        string[] output = dinosaurs.GetRange(2, 3).ToArray();
        
        Console.WriteLine();
        foreach( string dinosaur in output )
        {
            Console.WriteLine(dinosaur);
        }
    }
}

/* This code example produces the following output:

Capacity: 3

Brachiosaurus
Amargasaurus
Mamenchisaurus

AddRange(dinosaurs)

Brachiosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Amargasaurus
Mamenchisaurus

RemoveRange(2, 2)

Brachiosaurus
Amargasaurus
Amargasaurus
Mamenchisaurus

InsertRange(3, input)

Brachiosaurus
Amargasaurus
Amargasaurus
Tyrannosaurus
Deinonychus
Velociraptor
Mamenchisaurus

output = dinosaurs.GetRange(2, 3).ToArray()

Amargasaurus
Tyrannosaurus
Deinonychus
 */

 

posted @ 2016-05-11 16:23  霓裳依旧  阅读(11274)  评论(0编辑  收藏  举报