您的位置:首页 > 理论基础 > 数据结构算法

03.C#数据结构ArrayList、Hashtable、List泛型、Dictionary字典

2016-01-07 17:26 417 查看
Program.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace Test1
{
class Program
{
static void Main(string[] args)
{
/*
一.ArrayList(使用using System.Collections;)

*/
ArrayList list1 = new ArrayList();
//1.增
// list1.Add("hello");
list1.Add(2);
list1.Add(1);
list1.Add(3);

//2.删
list1.Remove(3);
list1.RemoveAt(0);

//3.改
list1.Insert(0, 5);

list1.Sort();//排序(数据类型必须相同)
list1.Contains(2);
foreach (object item in list1)
{
// Console.WriteLine(item);
}

/*
二.Hashtable( 使用using System.Collections;)

*/
Hashtable hash1 = new Hashtable();
hash1.Add(1, "hello");
hash1.Add(2, "world");
hash1.Add(3, "C#");
//Console.WriteLine(hash1[1]);

//1.遍历输出键
var keys = hash1.Keys;
foreach (object item in keys)
{
// Console.WriteLine(item);
}

//2.使用遍历器
var ie = hash1.GetEnumerator();//获取遍历器
while (ie.MoveNext())
{
//ie.MoveNext()本集合下一行还有就返回true
// Console.WriteLine("{0},{1}", ie.Key, ie.Value);
}

/*
三:泛型:
1.引用using System.Collections.Generic;
2.使用泛型就是为了保证数据类型的安全:如在使用ArrayList是无法保证类型的一致性。
3.使用的时候必须规定数据的类型,保证了安全。
*/

List<int> list2 = new List<int>();
list2.Add(1);
list2.Add(3);
list2.Add(2);

for (int i = 0;i< list2.Count;i++) {
//Console.WriteLine(list1[i]);
}

/*
四:字典:
1.引用using System.Collections.Generic;
2.可以规定键值的类型

*/

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("01","张三");
dic.Add("02", "李四");

//Console.WriteLine(dic["01"]);

//1.一般遍历输出
var keys2 = dic.Keys;
foreach (string item in keys2) {
//Console.WriteLine(dic[item]);
}
//2.也可以用遍历器访问
var ie2 = dic.GetEnumerator();
while (ie.MoveNext()) {
//Console.WriteLine("{0},{1}",ie2.Current.Key,ie2.Current.Value);
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息