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