System.Collections 的常用集合介绍

所有类型都继承object类型,因此任何类型的对象都能被组合到object类型的单一集合中。c#的foreach就要求遍历的集合的元素是同一类型。

System.Collections 类通常可以分为三种类型:

  • 常用集合。

    这些集合是数据集合的常见变体,如哈希表、队列、堆栈、字典和列表。常用集合有泛型和非泛型之分。

  • 位集合。

    这些集合中的元素均为位标志。它们的行为与其他集合稍有不同。

  • 专用集合。

    这些集合都具有专门的用途,通常用于处理特定的元素类型,如 StringDictionary

ArrayList

ArrayList 类似于array, 但是其容量是不固定的。如果要存储的对象数字超过了其容量,那么新的内存区域原有容量的2倍的对象。并重新定位这些对象。ArrayList的最初默认容量为16项。

a.是数组的复杂版本.Array是数组是固定的,而ArrayList类是根据需要自动扩展的.如果更改了Array.Capacity属性的值,则自动进行内存重新分配和元素复制.  
b.ArrayList提供添加/或移除某一范围元素的方法.在Array中,只能一次获取或设置一个元素的值.  
c.使用   Synchronized方法可以很容易地创建ArrayList的同步版本.而Array将一直保持它,直到用户实现同步为止.  

d.ArrayList提供将只读和固定大小包装返回到集合的方法.而Array不提供.  
e.Array提供ArrayList所不具有的某些灵活性.   
          I.可以设置Array的下限,但ArrayList的下限始终为零.   
          II.Array可以具有多个维度,而ArrayList始终是唯一的.   
         III.Array是特定类型(不是Object),比ArrayList性能好. ArrayList在存储和检索时经常发生拆箱和装箱操作现象.                                        

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Collections;


namespace  ArrayList1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            
string[] str = new string[] "aaa""bbb""ccc""ddd" };

            ArrayList aaList 
= new ArrayList(20);
            aaList.Capacity 
= 30;
           
foreach (string strssss in str)
               aaList.Add(strssss);
            Console.WriteLine(
"arraylist contains");
            
foreach (string str1 in aaList)
            
{
                Console.Write(str1 
+ " ");
            }

            Console.WriteLine();
            
string[] strss = (string[])aaList.ToArray(typeof(string));
            Console.WriteLine(
"copy ArrayList to a string arry");
            
for (int i = 0; i < strss.Length; i++)
                Console.Write(strss[i]
+" ");
            Console.WriteLine();

            Console.WriteLine(
"add a new string array to the arraylist");
            
string[] staa = new string[] "AADFAS""FAFADSDAF" };
            aaList.AddRange(staa);
            
foreach (string str1 in aaList)
            
{
                Console.Write(str1 
+" ");
            }

            Console.WriteLine();
            aaList.Insert(
2"dafsadfs10");
            Console.WriteLine(
"insert new element at index 2");
            
foreach (string str1 in aaList)
            
{
                Console.Write(str1 
+ " ");
            }

            Console.WriteLine();

            Console.WriteLine(
"remove element at index 3");
            aaList.RemoveAt(
3);

            
for (int i = 0; i < aaList.Count;i ++
            
{
                Console.Write(aaList [i] 
+ " ");
            }

            Console.WriteLine();

            Console.WriteLine(
"remove an object element");
            
//remove 方法花费时间比较长,须在数组中进行线形搜索
            aaList.Remove("AADFAS");
            
for (int i = 0; i < aaList.Count; i++)
            
{
                Console.Write(aaList[i] 
+ " ");
            }

            Console.WriteLine();

            Console.WriteLine(
"get the range at index 2, length = 2 from the original arraylist to a new one");
            ArrayList arrayList 
= new ArrayList(aaList.GetRange(22));
            
for (int i = 0; i < arrayList.Count; i++)
                Console.Write(arrayList[i] 
+ " ");
            Console.WriteLine();

            String[] strArray 
= (String[])arrayList.ToArray(typeof(string));
        }

    }

}

 

 

Stack

stack 是一种适合于处理应用程序使用完后就删除的临时数据项的类型集合。 他以后进先出的结构创建集合。

 a.如果需要以信息在集合中存储的相反顺序来访问这些信息,请使用Queue.  
b.Push在Stack的顶部插入一个元素.   Pop在Stack的顶部移除一个元素.   Peek返回处于Stack顶部的元素,但不将其从栈顶上移除.
  

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Collections;

namespace  StackExample
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            Stack stackExample 
= new Stack(30);
            stackExample.Push(
"abc");
            stackExample.Push(
"2");
            stackExample.Push(
"3");
            
// deep copy, create a new string[] class
            string[] str = new string [5];
            stackExample.CopyTo(str, 
0);

            
//shallow copy. 
            Stack str123 = (Stack)stackExample.Clone();
            
//original stack elements
            for (int i = 0; i < str.Length; i++)
                Console .Write(str[i]
+" ");
            Console.WriteLine();
            str123.Push(
"4");
            Console.WriteLine(
"original stack elements");
            
foreach (string strTemp in stackExample)
            
{
                Console.Write(strTemp 
+ " ");
            }

            Console.WriteLine();
            Console.WriteLine(
"modified stack elements");
            
foreach (string strTemp in str123)
            
{
                Console.Write(strTemp 
+ " ");
            }

            Console.WriteLine();
            
object [] strs = stackExample.ToArray();
            
for (int i = 0; i < strs.Length; i++)
                Console.Write(strs[i] 
+ " ");
        }

    }

}

Queue

使用queue类和他所健的集合与stack类似。主要区别是queue类以先进先出的结构来建集合。

a.如果需要以信息在集合中存储的相同顺序来访问这些信息,请使用Queue.  
b.Enqueue将一个元素添加到Queue的队尾.   Dequeue从Queue处移除最旧的元素.   Peek从Queue的开始处返回最旧的元素,但不将从Queue中移除.
  

SortedList

sortedlist类创建的集合,会给每个项都会指定一个用于引用该项得标识键。

a.SortedList类类似于Hashtable和ArrayList间的混合.  
b.SortedList的每一元素都是键对值,提供只返回键列表或只返回值列表的方法.  
c.如果想要一个保留键和值的集合,并且还需要索引的灵活性,则使用SortList.
  

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Collections;

namespace  Sortedist1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            SortedList sl 
= new SortedList();
            sl.Add(
1"aaa");
            sl.Add(
2"bbb");
            sl.Add(
3"ccc");
            
for (int i = 0; i < sl.Count; i++)
            
{
                Console.WriteLine(
"key " + sl.GetKey(i) + " item " + sl.GetByIndex(i));
            }

            
foreach (string str in sl.GetValueList())
                Console.WriteLine(
"item " + str);
            
foreach (int str in sl.GetKeyList())
                Console.WriteLine(
"item " + str);
            sl.Remove(
2);
            
for (int i = 0; i < sl.Count; i++)
            
{
                Console.WriteLine(
"index "+ i+ " key " + sl.GetKey(i) + " item " + sl.GetByIndex(i));
            }

            SortedList sl2 
= sl.Clone() as SortedList;
            sl2.Add(
4"dd");
            
            Console.WriteLine(
"sl2 after clone");
            
for (int i = 0; i < sl2.Count; i++)
            
{
                Console.WriteLine(
"index " + i + " key " + sl2.GetKey(i) + " item " + sl2.GetByIndex(i));
            }

            Console.WriteLine(
"sl1 after clone");
            
for (int i = 0; i < sl.Count; i++)
            
{
                Console.WriteLine(
"index " + i + " key " + sl.GetKey(i) + " item " + sl.GetByIndex(i));
            }


        }

    }

}

Hashtable

a.Hashtable类基于IDictionary接口,因此该集合中的每一元素是键和值对.   
b.Object.GetHashCode方法为其自身生成哈希代码.还可以通过使用Hashtable构造函数,为所有元素指定一个哈希函数.  

using  System;
using  System.Collections;

class  Example
{
    
public static void Main()
    
{
        
// Create a new hash table.
        
//
        Hashtable openWith = new Hashtable();

        
// Add some elements to the hash table. There are no 
        
// duplicate keys, but some of the values are duplicates.
        openWith.Add("txt""notepad.exe");
        openWith.Add(
"bmp""paint.exe");
        openWith.Add(
"dib""paint.exe");
        openWith.Add(
"rtf""wordpad.exe");

        
// The Add method throws an exception if the new key is 
        
// already in the hash table.
        try
        
{
            openWith.Add(
"txt""winword.exe");
        }

        
catch
        
{
            Console.WriteLine(
"An element with Key = "txt" already exists.");
        }


        
// The Item property is the default property, so you 
        
// can omit its name when accessing elements. 
        Console.WriteLine("For key = "rtf", value = {0}.", openWith["rtf"]);

        
// The default Item property can be used to change the value
        
// associated with a key.
        openWith["rtf"= "winword.exe";
        Console.WriteLine(
"For key = "rtf", value = {0}.", openWith["rtf"]);

        
// If a key does not exist, setting the default Item property
        
// for that key adds a new key/value pair.
        openWith["doc"= "winword.exe";

        
// ContainsKey can be used to test keys before inserting 
        
// them.
        if (!openWith.ContainsKey("ht"))
        
{
            openWith.Add(
"ht""hypertrm.exe");
            Console.WriteLine(
"Value added for key = "ht": {0}", openWith["ht"]);
        }


        
// When you use foreach to enumerate hash table elements,
        
// the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        
foreach( DictionaryEntry de in openWith )
        
{
            Console.WriteLine(
"Key = {0}, Value = {1}", de.Key, de.Value);
        }


        
// To get the values alone, use the Values property.
        ICollection valueColl = openWith.Values;

        
// The elements of the ValueCollection are strongly typed
        
// with the type that was specified for hash table values.
        Console.WriteLine();
        
foreachstring s in valueColl )
        
{
            Console.WriteLine(
"Value = {0}", s);
        }


        
// To get the keys alone, use the Keys property.
        ICollection keyColl = openWith.Keys;

        
// The elements of the KeyCollection are strongly typed
        
// with the type that was specified for hash table keys.
        Console.WriteLine();
        
foreachstring s in keyColl )
        
{
            Console.WriteLine(
"Key = {0}", s);
        }


        
// Use the Remove method to remove a key/value pair.
        Console.WriteLine(" Remove("doc")");
        openWith.Remove(
"doc");

        
if (!openWith.ContainsKey("doc"))
        
{
            Console.WriteLine(
"Key "doc" is not found.");
        }

    }

}


/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Value added for key = "ht": hypertrm.exe

Key = dib, Value = paint.exe
Key = txt, Value = notepad.exe
Key = ht, Value = hypertrm.exe
Key = bmp, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe

Value = paint.exe
Value = notepad.exe
Value = hypertrm.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe

Key = dib
Key = txt
Key = ht
Key = bmp
Key = rtf
Key = doc

Remove("doc")
Key "doc" is not found.
 
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值