C#中几种常用的集合的用法ArrayList集合HashTable集合List<T>集合Dictionary<K,V>集合及区别

原文链接:https://www.cnblogs.com/sujulin/p/7137938.html

集合:将一推数据类型相同的数据放入到一个容器内,该容器就是数组:内存中开辟的一连串空间。

非泛型集合

ArrayList集合:

ArrayList是基于数组实现的,是一个动态数组,其容量能自动 增长

ArrayList的命名空间System.Collections

常用方法如下:

 

示例
static void Main(string[] args)

       {
            ArrayList list = new ArrayList();
             //添加单个元素
           list.Add(true);
           list.Add(1);
           list.Add("张三");
            //添加集合元素
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            //list.AddRange(list);
        //list.Clear();清空所有元素
        //list.Remove(true);删除单个元素 写谁就删出谁
       //list.RemoveAt(0);根据下标去删除元素
        //list.RemoveRange(0, 3);根据下标去移除一定范围的元素
        //list.Insert(1, "插入的");在指定的位置插入一个元素
        //list.InsertRange(0, new string[] { "张三", "李四" });在指定的位置插入一个集合
        //bool b = list.Contains(1);判断是否包含某个指定的元素
       list.Add("大男孩");
       if (!list.Contains("大男孩"))
       {
            list.Add("大男孩");
        }else{
            Console.WriteLine("已经有了");
         }<br>              //循环打印
         for (int i = 0; i &lt; list.Count; i++)
        {
            Console.WriteLine(list[i]);
        }
        // list.Sort();//升序排列
       //list.Reverse();反转
        Console.ReadKey();
    }

 ArrayList集合遍历的三种方式:

  foreach(Object   item  in  list){
       Console.writer(item.ToString()+"");
 }

Ienumertor num=list.GetEnumertor();

 while(num.MoveNext()){
 Console.writer(num.Curret.ToString()+"");
}

 for(int i=0;i<list.count;i++){
Console.Writer(list[i].ToString()+"");
}

HashTable集合:

HashTable的常用属性和方法:

         示例:
//创建一个HashTable
Hashtable openWith = new Hashtable();
//为HashTable添加元素,不能有重复的key,但可以有重复的值
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

//通过key获得值
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
//重新赋值
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
            //判断是否包含特定的key
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
}
HashTable集合遍历的方式:

泛型集合
List<T>集合:
特点:

1)、可通过索引访问的对象的强类型。

2)、是ArrayList类的泛型等效类。

3)、可以使用一个整数索引访问此集合中的元素;索引从 零开始。

4)、可以接收null空引用(VB中的Nothing)。

5)、允许重复元素。

List<T>集合的方法:

01. Add    将对象添加到 List<T> 的结尾处。

02. AddRange    将指定集合的元素添加到 List<T> 的末尾。

03. AsReadOnly    返回当前集合的只读 IList<T> 包装。  

04. BinarySearch(T)    使用默认的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引。  

05. BinarySearch(T, IComparer<T>)   使用指定的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引。  

 06 . BinarySearch(Int32, Int32, T, IComparer<T>)  使用指定的比较器在已排序 List<T> 的某个元素范围中搜索元素,并返回该元素从零开始的索引。   

 07. Clear    从 List<T> 中移除所有元素。    

08. Contains    确定某元素是否在 List<T> 中。  

09. ConvertAll<TOutput>  将当前 List<T> 中的元素转换为另一种类型,并返回包含转换后的元素的列表。

10. CopyTo(T[])    将整个 List<T> 复制到兼容的一维数组中,从目标数组的开头开始放置。  

11. Exists     确定 List<T> 是否包含与指定谓词所定义的条件相匹配的元素。

12. Find   搜索与指定谓词所定义的条件相匹配的元素,并返回整个 List<T> 中的第一个匹配 元素。  

13 .FindIndex(Predicate<T>)    搜索与指定谓词所定义的条件相匹配的元素,并返回整个List <T> 中第一个匹配元素的从零开始的索引。  

14. ForEach   对 List<T> 的每个元素执行指定操作。  GetEnumerator    返回循环访问 List<T> 的枚举器。  

15 . IndexOf(T) 搜索指定的对象,并返回整个 List<T> 中第一个匹配项的从零开始的索引。  

16. Insert    将元素插入 List<T> 的指定索引处。

17. InsertRange    将集合中的某个元素插入 List<T> 的指定索引处。    

18. LastIndexOf(T)    搜索指定的对象,并返回整个 List<T> 中最后一个匹配项的从零开始的索引。    

19. Remove    从 List<T> 中移除特定对象的第一个匹配项。    

20. Reverse()     将整个 List<T> 中元素的顺序反转。    

21. Sort()     使用默认比较器对整个 List<T> 中的元素进行排序。  

List<T>集合遍历的二种方法:



Dictionary<K,V>集合:
常用的方法和属性:
特点:
从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
  1.  任何键都必须是唯一的

    键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值

    Key和Value可以是任何类型(string,int,custom class 等)

  1. Comparer:           获取用于确定字典中的键是否相等的 IEqualityComparer。

      Count:                  获取包含在 Dictionary中的键/值对的数目。

      Item:                    获取或设置与指定的键相关联的值。

      Keys:                   获取包含 Dictionary中的键的集合。

      Values:                获取包含 Dictionary中的值的集合。

      Add:                    将指定的键和值添加到字典中。

      Clear:                  从 Dictionary中移除所有的键和值。

      ContainsKey:      确定 Dictionary是否包含指定的键。

      ContainsValue:   确定 Dictionary是否包含特定值。             

      GetEnumerator:  返回循环访问 Dictionary的枚举数。

      GetType:             获取当前实例的 Type。 (从 Object 继承。)

      Remove:             从 Dictionary中移除所指定的键的值。

      ToString:             返回表示当前 Object的 String。 (从 Object 继承。)

      TryGetValue:      获取与指定的键相关联的值。

  1. 创建及初始化

     Dictionary<int,string>myDictionary=newDictionary<int,string>();

    添加元素

    myDictionary.Add(1,"C#");

    myDictionary.Add(2,"C++");

    myDictionary.Add(3,"ASP.NET");

    myDictionary.Add(4,"MVC");

  2. 通过Key查找元素

    if(myDictionary.ContainsKey(1))

    {

    Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);

     }

    通过Remove方法移除指定的键值

    myDictionary.Remove(1);

    if(myDictionary.ContainsKey(1))

    ...{

     Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);

      }

        else

       {

      Console.WriteLine("不存在 Key : 1"); 

     }

   Dictionary<T>集合遍历的方式:
  1.  通过KeyValuePair遍历元素

    foreach(KeyValuePair<int,string>kvp in myDictionary)

    ...{

    Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);

    }

    仅遍历键 Keys 属性

    Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;

    foreach(intkeyinkeyCol)

    ...{

    Console.WriteLine("Key = {0}", key);

    }

    仅遍历值 Valus属性

    Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;

    foreach(stringvalueinvalueCol)

    ...{

    Console.WriteLine("Value = {0}", value);

    }

 
 

1)、Dictionary<K,V> students=new Dictionary<K,V>();   其中“K”为占位符,具体定义时用存储键“Key”的数据类型代替,“V”也是占位符,用元素的值“Value”的数据类型代替,这样就在定义该集合时,声明了存储元素的键和值的数据类型,保证了类型的安全性。  

2)、Dictionary<K,V>中元素的操作方法与HashTable相似,添加元素,获取元素,删除元素,遍历集合元素的方法基本相同。  

3)、Dictionary<K,V>和HashTable的区别   Dictionary<K,V>和HashTable的相同点: 添加元素,删除元素,通过键访问值的方法相同。  

         Dictionary<K,V>和HashTable的不同点:   Dictionary<K,V>对添加的元素具有类型约束,HashTable可添加任意类型的元素。  

                                                                             Dictionary<K,V>不需要装箱、拆箱操作,HashTable添加时装箱,读取时拆箱。 

ArrayList与List<T>的区别:


HashTable与Dictionary<K,T>的区别:



集合:将一推数据类型相同的数据放入到一个容器内,该容器就是数组:内存中开辟的一连串空间。

非泛型集合

ArrayList集合:

ArrayList是基于数组实现的,是一个动态数组,其容量能自动 增长

ArrayList的命名空间System.Collections

常用方法如下:

 

示例
static void Main(string[] args)

       {
            ArrayList list = new ArrayList();
             //添加单个元素
           list.Add(true);
           list.Add(1);
           list.Add("张三");
            //添加集合元素
            list.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            //list.AddRange(list);
        //list.Clear();清空所有元素
        //list.Remove(true);删除单个元素 写谁就删出谁
       //list.RemoveAt(0);根据下标去删除元素
        //list.RemoveRange(0, 3);根据下标去移除一定范围的元素
        //list.Insert(1, "插入的");在指定的位置插入一个元素
        //list.InsertRange(0, new string[] { "张三", "李四" });在指定的位置插入一个集合
        //bool b = list.Contains(1);判断是否包含某个指定的元素
       list.Add("大男孩");
       if (!list.Contains("大男孩"))
       {
            list.Add("大男孩");
        }else{
            Console.WriteLine("已经有了");
         }<br>              //循环打印
         for (int i = 0; i &lt; list.Count; i++)
        {
            Console.WriteLine(list[i]);
        }
        // list.Sort();//升序排列
       //list.Reverse();反转
        Console.ReadKey();
    }

 ArrayList集合遍历的三种方式:

  foreach(Object   item  in  list){
       Console.writer(item.ToString()+"");
 }

Ienumertor num=list.GetEnumertor();

 while(num.MoveNext()){
 Console.writer(num.Curret.ToString()+"");
}

 for(int i=0;i<list.count;i++){
Console.Writer(list[i].ToString()+"");
}

HashTable集合:

HashTable的常用属性和方法:

         示例:
//创建一个HashTable
Hashtable openWith = new Hashtable();
//为HashTable添加元素,不能有重复的key,但可以有重复的值
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

//通过key获得值
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
//重新赋值
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
            //判断是否包含特定的key
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
}
HashTable集合遍历的方式:

泛型集合
List<T>集合:
特点:

1)、可通过索引访问的对象的强类型。

2)、是ArrayList类的泛型等效类。

3)、可以使用一个整数索引访问此集合中的元素;索引从 零开始。

4)、可以接收null空引用(VB中的Nothing)。

5)、允许重复元素。

List<T>集合的方法:

01. Add    将对象添加到 List<T> 的结尾处。

02. AddRange    将指定集合的元素添加到 List<T> 的末尾。

03. AsReadOnly    返回当前集合的只读 IList<T> 包装。  

04. BinarySearch(T)    使用默认的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引。  

05. BinarySearch(T, IComparer<T>)   使用指定的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引。  

 06 . BinarySearch(Int32, Int32, T, IComparer<T>)  使用指定的比较器在已排序 List<T> 的某个元素范围中搜索元素,并返回该元素从零开始的索引。   

 07. Clear    从 List<T> 中移除所有元素。    

08. Contains    确定某元素是否在 List<T> 中。  

09. ConvertAll<TOutput>  将当前 List<T> 中的元素转换为另一种类型,并返回包含转换后的元素的列表。

10. CopyTo(T[])    将整个 List<T> 复制到兼容的一维数组中,从目标数组的开头开始放置。  

11. Exists     确定 List<T> 是否包含与指定谓词所定义的条件相匹配的元素。

12. Find   搜索与指定谓词所定义的条件相匹配的元素,并返回整个 List<T> 中的第一个匹配 元素。  

13 .FindIndex(Predicate<T>)    搜索与指定谓词所定义的条件相匹配的元素,并返回整个List <T> 中第一个匹配元素的从零开始的索引。  

14. ForEach   对 List<T> 的每个元素执行指定操作。  GetEnumerator    返回循环访问 List<T> 的枚举器。  

15 . IndexOf(T) 搜索指定的对象,并返回整个 List<T> 中第一个匹配项的从零开始的索引。  

16. Insert    将元素插入 List<T> 的指定索引处。

17. InsertRange    将集合中的某个元素插入 List<T> 的指定索引处。    

18. LastIndexOf(T)    搜索指定的对象,并返回整个 List<T> 中最后一个匹配项的从零开始的索引。    

19. Remove    从 List<T> 中移除特定对象的第一个匹配项。    

20. Reverse()     将整个 List<T> 中元素的顺序反转。    

21. Sort()     使用默认比较器对整个 List<T> 中的元素进行排序。  

List<T>集合遍历的二种方法:



Dictionary<K,V>集合:
常用的方法和属性:
特点:
从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
  1.  任何键都必须是唯一的

    键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值

    Key和Value可以是任何类型(string,int,custom class 等)

  1. Comparer:           获取用于确定字典中的键是否相等的 IEqualityComparer。

      Count:                  获取包含在 Dictionary中的键/值对的数目。

      Item:                    获取或设置与指定的键相关联的值。

      Keys:                   获取包含 Dictionary中的键的集合。

      Values:                获取包含 Dictionary中的值的集合。

      Add:                    将指定的键和值添加到字典中。

      Clear:                  从 Dictionary中移除所有的键和值。

      ContainsKey:      确定 Dictionary是否包含指定的键。

      ContainsValue:   确定 Dictionary是否包含特定值。             

      GetEnumerator:  返回循环访问 Dictionary的枚举数。

      GetType:             获取当前实例的 Type。 (从 Object 继承。)

      Remove:             从 Dictionary中移除所指定的键的值。

      ToString:             返回表示当前 Object的 String。 (从 Object 继承。)

      TryGetValue:      获取与指定的键相关联的值。

  1. 创建及初始化

     Dictionary<int,string>myDictionary=newDictionary<int,string>();

    添加元素

    myDictionary.Add(1,"C#");

    myDictionary.Add(2,"C++");

    myDictionary.Add(3,"ASP.NET");

    myDictionary.Add(4,"MVC");

  2. 通过Key查找元素

    if(myDictionary.ContainsKey(1))

    {

    Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);

     }

    通过Remove方法移除指定的键值

    myDictionary.Remove(1);

    if(myDictionary.ContainsKey(1))

    ...{

     Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);

      }

        else

       {

      Console.WriteLine("不存在 Key : 1"); 

     }

   Dictionary<T>集合遍历的方式:
  1.  通过KeyValuePair遍历元素

    foreach(KeyValuePair<int,string>kvp in myDictionary)

    ...{

    Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);

    }

    仅遍历键 Keys 属性

    Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;

    foreach(intkeyinkeyCol)

    ...{

    Console.WriteLine("Key = {0}", key);

    }

    仅遍历值 Valus属性

    Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;

    foreach(stringvalueinvalueCol)

    ...{

    Console.WriteLine("Value = {0}", value);

    }

 

1)、Dictionary<K,V> students=new Dictionary<K,V>();   其中“K”为占位符,具体定义时用存储键“Key”的数据类型代替,“V”也是占位符,用元素的值“Value”的数据类型代替,这样就在定义该集合时,声明了存储元素的键和值的数据类型,保证了类型的安全性。  

2)、Dictionary<K,V>中元素的操作方法与HashTable相似,添加元素,获取元素,删除元素,遍历集合元素的方法基本相同。  

3)、Dictionary<K,V>和HashTable的区别   Dictionary<K,V>和HashTable的相同点: 添加元素,删除元素,通过键访问值的方法相同。  

         Dictionary<K,V>和HashTable的不同点:   Dictionary<K,V>对添加的元素具有类型约束,HashTable可添加任意类型的元素。  

                                                                             Dictionary<K,V>不需要装箱、拆箱操作,HashTable添加时装箱,读取时拆箱。 

ArrayList与List<T>的区别:


HashTable与Dictionary<K,T>的区别:



猜你喜欢

转载自www.cnblogs.com/sunny3158/p/13405997.html