List
1. List(T).AddRange 方法
将指定集合的元素添加到 List(T)的末尾。
C#
public void AddRange(
IEnumerable<T> collection
)
public void AddRange(
IEnumerable<T> collection
)
参数
- collection
- 类型:System.Collections.Generic.IEnumerable(T)
一个集合,其元素应被添加到 List(T)的末尾。集合自身不能为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing),但它可以包含为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing) 的元素(如果类型 T 为引用类型)。
代码using System;
using System.Collections.Generic;
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
string[] input = { "Brachiosaurus",
"Amargasaurus",
"Mamenchisaurus" };
List<string> dinosaurs = new List<string>(input);
outputBlock.Text += String.Format("\nCapacity: {0}", dinosaurs.Capacity) + "\n";
outputBlock.Text += "\n";
foreach (string dinosaur in dinosaurs)
{
outputBlock.Text += dinosaur + "\n";
}
outputBlock.Text += "\nAddRange(dinosaurs)" + "\n";
dinosaurs.AddRange(dinosaurs);
outputBlock.Text += "\n";
foreach (string dinosaur in dinosaurs)
{
outputBlock.Text += dinosaur + "\n";
}
outputBlock.Text += String.Format("\nRemoveRange(2, 2)") + "\n";
dinosaurs.RemoveRange(2, 2);
outputBlock.Text += "\n";
foreach (string dinosaur in dinosaurs)
{
outputBlock.Text += dinosaur + "\n";
}
input = new string[] { "Tyrannosaurus",
"Deinonychus",
"Velociraptor"};
outputBlock.Text += String.Format("\nInsertRange(3, input)") + "\n";
dinosaurs.InsertRange(3, input);
outputBlock.Text += "\n";
foreach (string dinosaur in dinosaurs)
{
outputBlock.Text += dinosaur + "\n";
}
outputBlock.Text += String.Format("\noutput = dinosaurs.GetRange(2, 3).ToArray()") + "\n";
string[] output = dinosaurs.GetRange(2, 3).ToArray();
outputBlock.Text += "\n";
foreach (string dinosaur in output)
{
outputBlock.Text += dinosaur + "\n";
}
}
}
/* 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
*/