C#中提供我们这些集合ArryList,hashtable,list,Dictionary<string,values>:这些集合为我们提供了许多不同场合中的方便。
ArrayList的用法:
ArrayList class1 = new ArrayList(2);
Student s1 = new Student("zs", 23, Genders.男);
Student s2 = new Student("ls", 22, Genders.女);
Student s3 = new Student("ww", 20, Genders.女);
Student s4 = new Student("ml", 23, Genders.女);
//往列表集合添加数据(添加项);
//object obj1 = (object)s1;
Console.WriteLine(class1.Count);
Console.WriteLine(class1.Capacity);
class1.Add(s1);
//集合的实际元素数
Console.WriteLine(class1.Count);
//集合预分配大小
Console.WriteLine(class1.Capacity);
class1.Add(s2);
Console.WriteLine(class1.Count);
Console.WriteLine(class1.Capacity);
class1.Add(s3);
Console.WriteLine(class1.Count);
Console.WriteLine(class1.Capacity);
//迭代遍历
foreach (object obj in class1)
{
Student s = (Student)obj;
s.SayHi();
}
hashtable的用法:
Hashtable ht = new Hashtable();
Student s1 = new Student("zs", 23, Genders.男);
Student s2 = new Student("ls", 22, Genders.女);
Student s3 = new Student("ww", 20, Genders.女);
//添加元素
ht.Add(s1.Name, s1);
ht.Add(s2.Name, s2);
ht.Add(s3.Name, s3);
//获取单个成员
//Student ss = (Student)ht["ls"];
// ss.SayHi();
//遍历操作
foreach (object obj in ht.Values)
{
Student s = (Student)obj;
s.SayHi();
}
//删除操作
ht.Remove("zs");
Console.WriteLine("删除以后");
foreach (object obj in ht.Keys)
{
Student s = (Student)ht[obj];
s.SayHi();
}
list的用法:
class LoadDataPerson
{
public void LoadData(List<Student> list)
{
Student s1 = new Student("zs", 24, Genders.男);
list.Add(s1);
}
}
class ReadDataPerson
{
public void ReadData(List<Student> list)
{
foreach (Student obj in list)
{
// ((Student)obj).SayHi();
obj.SayHi();
}
}
}
class Program
{
static void Main(string[] args)
{
// ArrayList list = new ArrayList();
List<Student> list = new List<Student>();
LoadDataPerson p1 = new LoadDataPerson();
p1.LoadData(list);
ReadDataPerson p2 = new ReadDataPerson();
p2.ReadData(list);
//添加数据
//list.Add(数据)
list[0].SayHi();
}
}
Dictionary<string,values>:
List<Student> list = new List<Student>();
Dictionary<string, Teacher> dic = new Dictionary<string, Teacher>();
Student s1 = new Student("zs", 22, Genders.男);
Student s2 = new Student("ww", 21, Genders.男);
Teacher t = new Teacher("ls", 33);
list.Add(s1);
list.Add(s2);
dic.Add(t.Name, t);
//获取单个元素
Student s = list[0];
foreach (Student sss in list)
{
sss.SayHi();
}
foreach (KeyValuePair<string,Teacher> e in dic)
{
if (e.Key == "lsd")
{
Console.Write(e.Value.Name);
}
else
{
Console.WriteLine("没有找到");
}
}
以上是这几个集合的使用。方便比较,所以将这几个写在一起。代码易看。