c#_集合類[ ArrayList]和鍵值對集合[Hashtable]

ArrayList[集合類]:可以添加、移除、遍歷;可變長度,用法和數組類似
數組特點:1.類型統一、2.長度固定
屬性:count(得到集合中的實際存放數據的個數)
方法:Add()添加   remove()移除  RemoveAt()從零開始索引,然後刪除對象。  ToArry()將集合轉成數組
引用快捷鍵:ctrl+Alt+F10


ArrayList[集合類]的建立、添加:
ArrayList arrayList=new ArrayList();
Console.WriteLine(arrayList.Count);
arrayList.Add(10);
arrayList.Add("HELLO WORLD");
arrayList.Add(3.45);
Console.WriteLine(arrayList.Count);//元素實際個數集合中
Console.WriteLine(arrayList.Capacity);
Console.ReadKey();


ArrayList[集合類]移除:
arrayList.Remove(3.45);


ArrayList[集合類]遍歷:
for(int i=0;i<9;i++)
{
arrayList.RemoveAt(0);
}
arrayList.TrimToSize();//縮減數組容量


Hashtable[健值對的集合]
Hashtable hashtable=new Hashtable();//Hashtable解析
//定義Person實例
Person YQQ=new Person(){Name="楊巧巧"};
hash.Add(YQQ.Name,YQQ);


Person Yy=new Person(){Name="尤越"};
hash.Add(Yy.Name,Yy);


//取值
Console.WriteLine( ((Person) hash["楊巧巧"]).Name);
方法:Add(object key,object value);
hash["key"]="修改";
Remove("key");


#region 
程序運行時不運行
#endregion


遍歷查找
for (int i = 0; i < arrInt.Length; i++)
{
 if (arrInt[i] == number)
  {
    b = true;
  }


}
if (b)
{
 Console.WriteLine("存在!");
 }
 else
{
 Console.WriteLine("不存在!");
 }
//健的地址是算出來的,不是遍歷得到得,所以才效率高
int[] arrInt={25,125,225,325,425,525,625};
int number=325;
bool b=false;
int index=number/100;
if(index<arrInt.Length)
{
Console.WriteLine("可能存在!");
Console.WriteLine(arrInt[index]);
}
else
{
Console.WriteLine("not exist");
}
Console.ReadKey();


if(hash.ContainsKey("張蘭"))
{
Console.WriteLine("包含");
}
else
{
Console.WriteLine("不包含");
}


遍歷Hsahtable
Hsahtable table=new Hsahtable();
table.Add("qq","YangQiaoQiao");
table.Add("lxf","LiuXiaoFei");
table.Add("zl","ZhangLan");
foreach(DictionaryEntry item in table)
{//DictionaryEntry是個結構體
Console.WriteLine(item.key+"  "+item.Value);
}
foreach(var item in table.Keys)
{
Console.WriteLine(itme);
}
foreach(var item in table.Value)
{
Console.WriteLine(itme);
}
//var 當變量沒有賦值時、變量可能是任意一種類型;一旦給變量賦了值,變量就成了值得類型。


作業:
1.把兩個(ArrayList)集合{"a","b","c","d"}和{"c","f","d","h"},  合併這兩個集合併除去重複項。合併爲一個新的arrayList集合對象
ArrayList arrayList1=new ArrayList(){"a","b","c","d"};
ArrayList arrayList2=new ArrayList(){"c","f","d","h"};
ArrayList arrayList3=new ArrayList();


arrayList3.AddRange(arryList1);
for(int i=0;i<arrayList2.count;i++)
{
if(!arrayList3.Contains(arrayList2[i]))
{
arrayList3.AddRange(arryList2[i]);
}
}
for(int i=0;i<arrayList3.Count;i++)
{
Console.WriteLine(arrayList3[i]);
}
2.隨機生成10個1-100之間的數,放到ArrayList中,要求這10個數不能重複,並且都是偶數。添加十次,但是會循環很多次。
ArrayList arrayRandom = new ArrayList();          
 Random random = new Random();
 while (arrayRandom.Count < 10)
{
 int ra= random.Next(1, 101);
 if (ra % 2 == 0)

if( !arrayRandom.Contains(ra))
{
 arrayRandom.Add(ra);
                      
 }
                
  }
 }
 Console.ReadKey();





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章