C#基础之一(集合)

C#基础之一(集合)

Posted on 2008-08-04 23:37 liuyan 阅读(17) 评论(0)   编辑 收藏 所属分类: ASP.NET

在C#当中,集合有我们常用的Arraylist(动态数组),Hashtable(关健字和值的查找表)和不常用的BitArray(位数组),Queue(先进先出的集合),SortedList(有序例表),Stack(后进先出的栈)等等.
其实集合就是将一组有序的数据组合在一起并能对其进行有效的处理.在这里我们主要介绍常用的Arraylist与Hashtable.

Arraylist
类似于一维动态数组,在Arraylist中可以存放任何对像,Arraylist的常用方法有以下三种:增加元素Add(),插入元素Insert(),删除元素Remove().
例:
首先要引入命名空间:using System.Collections;

         public   static   void  Main()
        
{
            ArrayList arr 
= new ArrayList();
            arr.Add(
10);//为集合添加一个值
            arr.Add(10);//添加第二个值
            arr.Insert(08);//在第0索引位置插入一个值8
            Console.WriteLine(arr.IndexOf(10,2));//搜索指从索引从0到2的值为10的数量.
            foreach (int a in arr)//遍历集合arr
            {
                Console.WriteLine(a);
            }


        }

Hashtable
是用来存入健/值对的集合,如果有需要同时存放健并对应有值的时候我们可以用Hashtable .
例:
         public   static   void  Main()
        
{
            Hashtable hash 
= new Hashtable(); //定义一个Hashtable集合
            hash.Add("one"1);//为集合中填加健与值
            hash.Add("two"2);
            hash.Add(
"three"3);
            hash.Add(
"four"4);
            
            
foreach (string a in hash.Keys)//遍历所有的健值
            {
                Console.WriteLine(
"{0},{1}", a, hash[a]);//输出健与值
            }

        }
 
System.Collections 命名空间包含接口和类,这些接口和类定义各种对象(如列表、队列、位数组、哈希表和字典)的集合。( 非泛型)
      System.Collections.Generic 命名空间包含定义 泛型集合的接口和类,泛型集合允许 用户创建强类型集合,它能提供比 非泛型强类型集合更好的类型安全性和性能。
System.Collections.Specialized 命名空间包含专用的和强类型的集合,例如,链接的列表词典、位向量以及只包含字符串的集合。

 

ArrayList 类:使用大小可按需动态增加的数组。

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Collections;
namespace  ConsoleApplication1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            ArrayList al 
= new ArrayList();
            al.Add(
100);//单个添加
            foreach (int number in new int[6937248 })
            
{
                al.Add(number);
//集体添加方法一
            }

            
int[] number2 = new int[21112 };
            al.AddRange(number2);
//集体添加方法二
            al.Remove(3);//移除值为3的
            al.RemoveAt(3);//移除第3个
            ArrayList al2 = new ArrayList(al.GetRange(13));//新ArrayList只取旧ArrayList一部份


            Console.WriteLine(
"遍历方法一:");
            
foreach (int i in al)//不要强制转换
            {
                Console.WriteLine(i);
//遍历方法一
            }


            Console.WriteLine(
"遍历方法二:");
            
for (int i = 0; i < al2.Count; i++)//数组是length
            {
                
int number = (int)al2[i];//一定要强制转换
                Console.WriteLine(number);//遍历方法二

            }

        }

    }

}

你可能感兴趣的:(C#)