.Net集合类
1 集合
1.1 Array
大小固定,Array 类是支持数组的语言实现的基类。但是,只有系统和编译器能够从 Array 类显式派生。用户应当使用由语言提供的数组构造。
1.2 ArrayList
大小可变,元素是object类型
1.3 List<T>
泛型集合不会发生装箱拆箱行为
性能:Array优于ArrayList,因为ArrayList元素是object类型,所以会发生装箱和拆箱行为
1000万条测试代码:
Stopwatch s1 = new Stopwatch();
s1.Start();
int[] a = new int[10000000];
for (int i = 0; i < 10000000; i++)
{
a[i] = i;
}
s1.Stop();
Console.WriteLine("{0}毫秒", s1.ElapsedMilliseconds);
s1.Start();
ArrayList b = new ArrayList();
for (int i = 0; i < 10000000; i++)
{
b.Add(i);
}
s1.Stop();
Console.WriteLine("{0}毫秒", s1.ElapsedMilliseconds);
2 队列
2.1Queue和Queue<T>
先进先出的集合
示例代码
Queue q = new Queue();
q.Enqueue("a");
q.Enqueue("b");
q.Dequeue();
q.Enqueue("c");
PrintQueue(q);
Console.WriteLine(q.Peek());
private static void PrintQueue(IEnumerable a)
{
foreach (object obj in a)
{
Console.WriteLine(obj);
}
}
3 栈
3.1 栈Stack和Stack<T>
后进先出集合
示例代码
Stack a = new Stack();
a.Push("a");
a.Push("b");
a.Pop();
a.Push("c");
Console.WriteLine(a.Peek());
PrintQueue(a);
4 链表
4.1 链表LinkedList<T>
优点:插入元素快
缺点:查找元素慢
示例代码:
LinkedList<int> a =new LinkedList<int>();
a.AddFirst(1);
a.AddFirst(2);
a.AddLast(3);
LinkedListNode<int> f1 = a.Find(2);
a.AddAfter(f1, 4);
a.AddLast(4);
foreach (int i in a)
{
Console.WriteLine(i);
}
5 有序表
5.1 SortedList和SortedList<TKey,TValue>
表示键/值对的集合,这些键值对按键排序并可按照键和索引访问。键不能重复
示例代码:
SortedList a = new SortedList();
a.Add("a", 1);
a.Add("b", 2);
a.Add("c", 3);
a.Add("e", 5);
a.Add("d", 4);
for (int i = 0; i < a.Count; i++)
{
Console.WriteLine("key:{0},value:{1}",a.GetKey(i),a.GetByIndex(i));
}
foreach (DictionaryEntry de in a)
{
Console.WriteLine("key:{0},value:{1}",de.Key,de.Value);
}
6 字典
6.1 Dictionary<TKey,TValue>和HashTable
Dictionary性能优于HashTable,因为HashTable的元素是object类型,会发生装箱和拆箱行为
示例代码:
Dictionary<string, int> d =new Dictionary<string, int>();
d.Add("a", 1);
d.Add("c", 3);
d.Add("b", 2);
foreach (KeyValuePair<string, int> kv in d)
{
Console.WriteLine("key:{0},value:{1}", kv.Key, kv.Value);
}
Hashtable h =new Hashtable();
h.Add("a", 11);
h.Add("b", 22);
h.Add("c", 33);
foreach (DictionaryEntry de in h)
{
Console.WriteLine("key:{0},value:{1}", de.Key, de.Value);
}
浙公网安备 33010602011771号