C#集合中的Add与AddRange方法

C#.NET的集合主要位于System.Collections和System.Collections.Generic(泛型)这两个namespace中。

1、System.Collections

比如ArrayList,其Add(继承自接口IList)和AddRange方法可用于想集合中添加元素。

代码示例:

(1)Add:添加单个元素

ArrayList myAL = new ArrayList();
myAL.Add( "The" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );

(2)AddRange:添加实现了ICollection接口的一个集合的所有元素到指定集合的末尾

ArrayList myAL = new ArrayList();
myAL.Add( "The" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );
 
Queue myQueue = new Queue();
myQueue.Enqueue( "jumped" );
myQueue.Enqueue( "over" );
myQueue.Enqueue( "the" );
myQueue.Enqueue( "lazy" );
myQueue.Enqueue( "dog" );
 
myAL.AddRange( myQueue );

2、System.Collections.Generic

泛型同样也有Add(继承自ICollection<T>)和AddRange两个方法。

代码示例:

(1)Add:添加单个元素

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

(2)AddRange:添加实现了接口IEnumerable<T>的一个泛型集合的所有元素到指定泛型集合末尾

string[] input = { "Brachiosaurus", "Amargasaurus", "Mamenchisaurus" };
List<string> dinosaurs = new List<string>(input);
dinosaurs.AddRange(dinosaurs);

参考资料:

http://msdn.microsoft.com/zh-cn/library/system.collections(v=vs.100).aspx

http://msdn.microsoft.com/zh-cn/library/system.collections.generic(v=vs.100).aspx

原文地址:https://www.cnblogs.com/AaronBlogs/p/7029487.html