06Net基础加强第六天-泛型集合与非泛型集合

本文深入解析了ArrayList和HashTable集合的使用方法,包括元素的增删查改、排序、清空等操作,以及如何通过实现IComparable接口或创建比较器类进行自定义排序。同时,介绍了如何遍历和操作键值对集合。

ArrayList集合
所有的集合都是通过数组实现的,只是对数组进行了封装。

//集合的长度不是固定的,另外集合可以存储各种不同数据类型的元素
            ArrayList arrayList = new ArrayList();
            arrayList.Add(1);
            arrayList.Add("嘎嘎嘎");
            arrayList.Add(true);
            arrayList.AddRange(new string[] { "sas", "sasa", "saas" });
            MessageBox.Show(arrayList[0].ToString());//集合也可以通过索引进行访问
            MessageBox.Show(arrayList.Count.ToString());//集合的count属性返回集合的元素个数
            MessageBox.Show(arrayList.Capacity.ToString());//集合的capacity属性返回的是集合的容量
            arrayList.Insert(0,"张三");//向集合中指定位置插入单个元素
            arrayList.InsertRange(1, new char[] { 'a', 'b', 'c' });//向集合中指定位置插入一个数组或者集合
            arrayList.Remove("张三");//删除集合中指定的元素
            arrayList.RemoveAt(2);//通过索引删除集合中的元素
            arrayList.RemoveRange(2, 3);//删除集合中一定范围的元素
            //如果想要清空集合中的所有元素,不要使用for循环遍历索引进行删除,因为集合的索引是随着元素的个数变化在变化的。要使用clear()方法进行清空。
            //而且也不能使用foreach循环进行清空集合中的元素,因为foreach循环是只读操作,无法对其修改。
            arrayList.Clear();//使用clear()方法清空集合中的所有元素
            arrayList.Contains("张三");//contains()方法用来判断集合中是否包含某个元素
            object[] o = arrayList.ToArray();//ToArray()方法将集合转成数组

实现IComparable接口,使这个类的实例能够进行排序

 public class Student: IComparable//实现了IComparable接口,重写了CompareTo(0方法,实现了Student这个类实例的比较
    {
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }

        int IComparable.CompareTo(object obj)
        {
            Student s = (Student)obj;
            //return this.Age - s.Age;//按照年龄升序排序
            //return s.Age - this.Age;//按照年龄降序排序
            //return this.Name.Length - s.Name.Length;//按照名字的长度进行升序排序
            return s.Name.Length - this.Name.Length;//按照名字的长度进行降序排列
        }
    }
            Student s1 = new Student();
            s1.Name = "张2三";
            s1.Age = 20;
            Student s2 = new Student();
            s2.Name = "李22222四";
            s2.Age = 25;
            Student s3 = new Student();
            s3.Name = "王33五";
            s3.Age = 29;
            Student s4 = new Student();
            s4.Name = "赵2222222六";
            s4.Age = 27;
            ArrayList arrayList = new ArrayList();
            arrayList.AddRange(new Student[] { s1, s2, s3, s4 });
            arrayList.Sort();
            for (int i = 0; i < arrayList.Count; i++)
            {
                MessageBox.Show(((Student)arrayList[i]).Name.ToString());
            }

另一种实现自定义类进行排序的方法,写一个比较器的类

 public class ComparerByNameLengthAsc : IComparer//实现了IComparer接口,这个类就是一个比较器
    {
        public int Compare(object x, object y)
        {
            Student s1 = x as Student;
            Student s2 = y as Student;
            return s1.Name.Length - s2.Name.Length;//按照名字的长度进行排序
        }
    }
            Student s1 = new Student();
            s1.Name = "张2三";
            s1.Age = 20;
            Student s2 = new Student();
            s2.Name = "李22222四";
            s2.Age = 25;
            Student s3 = new Student();
            s3.Name = "王33五";
            s3.Age = 29;
            Student s4 = new Student();
            s4.Name = "赵2222222六";
            s4.Age = 27;
            ArrayList arrayList = new ArrayList();
            arrayList.AddRange(new Student[] { s1, s2, s3, s4 });
            arrayList.Sort(new ComparerByNameLengthAsc());//因为ComparerByNameLengthAsc类实现了IComparer接口,所以此处直接传一个ComparerByNameLengthAsc对象就可以
            for (int i = 0; i < arrayList.Count; i++)
            {
                MessageBox.Show(((Student)arrayList[i]).Name.ToString());
            }

HashTable集合

            Hashtable ht = new Hashtable();
            //键值对集合在添加元素的时候键一定不能重复
            ht.Add(1, "张三");
            ht.Add(2, new Student() { Name = "李四", Age = 20 });
            MessageBox.Show(ht[1].ToString());
            MessageBox.Show(((Student)ht[2]).Name);
            bool b = ht.ContainsKey(1);//判断键值对集合中是否包含某个键
            MessageBox.Show(b.ToString());
            //遍历键值对的键
            foreach (var item in ht.Keys)
            {
                MessageBox.Show(item.ToString());
            }
            //遍历键值对中的值
            foreach (var item in ht)
            {
                MessageBox.Show(item.ToString());
            }
            //直接遍历键值对
            foreach (DictionaryEntry item in ht)//这里的类型不能用var,一定要用DictionaryEntry
            {
                MessageBox.Show("键:" + item.Key + "值:" + item.Value);
            }

集合练习

            ArrayList arrayList = new ArrayList();
            Random r = new Random();//Random对象一定要写在循环外面
            while (arrayList.Count < 10)
            {
                int num = r.Next(1, 101);
                if (num % 2 == 0 && !arrayList.Contains(num))
                {
                    arrayList.Add(num);
                }
            }
            foreach (var item in arrayList)
            {
                MessageBox.Show(item.ToString());
            }

泛型集合List和Dictionary<key,value>

          Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(0, "哈哈");
            dic.Add(1, "嘿嘿");
            //遍历键值对
            foreach (KeyValuePair<int,string> item in dic)//使用KeyValuePair<>
            {
                MessageBox.Show("键:" + item.Key + " 值:" + item.Value);
            }

集合练习:得到一个字符串中的每个字母出现的次数
char类还有很多静态方法,char.ToLower(),char.ToUpper()

        public Dictionary<char, int> GetCharCount(string str)//计算字符串中各个字母的个数
        {
            Dictionary<char, int> dic = new Dictionary<char, int>();
            //不区分大小写,先将字符串转成小写
            str = str.ToLower();
            for (int i = 0; i < str.Length; i++)
            {
                if(Char.IsLetter(str[i]))//Char类的IsLetter()方法可以直接判断一个字符是否是字母
                if (!dic.ContainsKey(str[i]))
                {
                    dic.Add(str[i], 1);
                }
                else
                {
                    dic[str[i]]++;
                }
            }
            return dic;
        }

集合练习:
案例:编写一个函数进行日期转换,将输入的中文日期转换为阿拉伯数字日期,(处理“十”的问题,1.*月十日 2.*月十三日 3.*月二十三日 4.*月三十日)

 public string DateConvert(string str)
    {
        StringBuilder sb = new StringBuilder();
        Dictionary<char, char> dic = new Dictionary<char, char>();
        string s = "零0 一1 二2 三3 四4 五5 六6 七7 八8 九9";
        string[] strs = s.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < strs.Length; i++)
        {
            dic.Add(strs[i][0], strs[i][1]);
        }
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] == '十')//当遇到“十”的时候进行处理
            {
                if (!dic.ContainsKey(str[i-1]) && !dic.ContainsKey(str[i+1]))
                {
                    sb.Append("10");
                }
                else if (!dic.ContainsKey(str[i-1]) && dic.ContainsKey(str[i+1]))
                {
                    sb.Append("1");
                }
                else if (dic.ContainsKey(str[i-1]) && !dic.ContainsKey(str[i+1]))
                {
                    sb.Append("0");
                }
            }
            else if (dic.ContainsKey(str[i]))//遇到集合中存在的直接进行转换
            {
                sb.Append(dic[str[i]]);
            }
            else//遇到其他字符转换成“-”
            {
                sb.Append("-");
            }
        }
        sb=sb.Remove(sb.Length - 1, 1);//移除最后一个字符“-”
        return sb.ToString();
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值