Lession11 集合和泛型(ArrayList方法、Arraylist类、ArrayList添加对象、ArrayList长度、HashTable类、Hashtable类练习-----)

目录

ArrayList方法:

ArrayList添加对象: 

 Arraylist类:

 ArrayList长度:

HashTable类: 

Hashtable类练习: 

 IComparable泛型接口排序:

IComparable接口实现排序: 

 IComparer泛型接口排序:

List泛型集合: 

 List泛型集合练习:

 var隐式类型:

 泛型集合常用的扩展方法:

 字典泛型集合:


ArrayList方法:

using System;
using System.Collections;

namespace ConsoleApp1         //ArrayList方法
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            //添加单个元素
            list.Add(1);
            list.Add("张三");
            list.Add(true);
            //添加集合或者数组
            list.AddRange(new int[] { 1, 2, 3, 4 });
            list.AddRange(list);

            //删除指定元素
            //list.Remove(true);
            删除指定下标元素
            //list.RemoveAt(0);
            //根据下标删除一定范围的元素
            // list.RemoveRange(0,2);
            //清除集合中的所有元素
            //list.Clear();

            //升序排序
            //list.Sort();
            //反转
            //list.Reverse();
            //在指定的位置插入一个元素
            // list.Insert(1,"插入的");
            //在指定位置插入一个数组
            // list.InsertRange(0,new string[] { "周一","周二"});

            //判断元素是否在这个集合中
            //bool b = list.Contains(1);
            //Console.WriteLine(b);
            //Console.WriteLine("---------------------");
            //if (!list.Contains("李腾"))
            //{
            //    list.Add("李腾");
            //}
            //else
            //{
            //    Console.WriteLine("已经有这个上课爱说话的学生了");
            //}

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

            Console.ReadKey();
        }
    }
}

ArrayList添加对象: 

using System;
using System.Collections;

namespace ConsoleApp1        //ArrayList添加对象
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();

            Student stu1 = new Student(1, "贾宝玉", 16, Gender.男);
            Student stu2 = new Student(2, "林黛玉", 14, Gender.女);
            Student stu3 = new Student(3, "薛宝钗", 15, Gender.女);
            list.Add(stu1);
            list.Add(stu2);
            list.Add(stu3);

            //按照索引取出对象
            Student s1 = (Student)list[1];
            s1.SayHi();
            Console.ReadKey();

        }
    }

    //学生类
    public class Student
    {
        public Student(int StuId, string Name, int Age, Gender Gender)
        {
            this.stuId = StuId;
            this.name = Name;
            this.age = Age;
            this.gender = Gender;
        }
        public int stuId;
        public string name;
        public int age;
        public Gender gender;
        public void SayHi()
        {
            Console.WriteLine($"我是{this.name},今年{this.age}");
        }

    }

    public enum Gender
    {
        男,
        女
    }
}

 Arraylist类:

using System;
using System.Collections;

namespace ConsoleApp1        //Arraylist类
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建的ArrayList集合
            ArrayList list = new ArrayList();
            //集合:很多数据的集合
            //数组:长度不可变,类型单一
            //集合:长度可以任意改变,类型随便

            //添加元素
            list.Add(1);
            list.Add(3.14);
            list.Add(true);
            list.Add("张三");
            list.Add('男');
            list.Add(1000M);
            list.Add(new int[] { 1, 2, 3, 4, 5, 6 });
            // list.Add(list);

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] is int[])
                {
                    for (int j = 0; j < ((int[])list[i]).Length; j++)
                    {
                        Console.WriteLine(((int[])list[i])[j]);
                    }
                }
                else
                {
                    Console.WriteLine(list[i]);
                }


            }

            Console.ReadKey();
        }
    }
}

 ArrayList长度:

using System;
using System.Collections;

namespace ConsoleApp1        //ArrayList长度
{
    /*
    * count:实际集合中的元素个数
    * Capacity:可以包含的元素个数
    * 集合中实际包含的元素个数(count)超过了可以包含的元素个数(Capacity)的时候
    * 集合就会向内存中申请一倍的空间,来保证集合的长度一直够用
    * 
    */
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(1);
            Console.WriteLine(list.Count);
            Console.WriteLine(list.Capacity);
            Console.ReadKey();
        }
    }
}

HashTable类: 

using System;
using System.Collections;

namespace ConsoleApp1        //HashTable类
{
    /*
    * HashTable  键值对集合     字典    张     zhang ->张
    * 在键值对集合中,我们是根据键找值的
    * 
    * 
    */
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个键值对集合对象
            Hashtable ht = new Hashtable();
            ht.Add(1, "张三");
            ht.Add(2, true);
            ht.Add(3, '无');
            ht.Add(false, "错误的");

            ht[6] = "新来的";   //这也是一种添加数据的方式  
            ht[1] = "把张三干掉";

            //ContainsKey  是否包含这个键
            if (!ht.ContainsKey("888发发发"))
            {
                ht.Add("888发发发", "李腾");
            }
            else
            {
                Console.WriteLine("已经有这个键了");
            }
            //清除所有元素
            //ht.Clear();
            // ht.Remove(6);
            //Console.WriteLine(ht[1]);
            //Console.WriteLine(ht[2]);
            //Console.WriteLine(ht[false]);
            //Console.WriteLine(ht[6]);
            //Console.WriteLine(ht["888发发发"]);

            foreach (var item in ht.Keys)
            {
                Console.WriteLine("键是:{0}=================>值是{1}", item, ht[item]);
                // Console.WriteLine(item);
            }

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

Hashtable类练习: 

using System;
using System.Collections;
using System.Text.RegularExpressions;

namespace ConsoleApp1        //Hashtable类练习
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            while (true)
            {
                //Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("=================请选择操作====================");
                Console.WriteLine("  1.添加联系人    2.查找    3.删除联系人   4. 修改联系人信息 ");
                Console.WriteLine("===============================================");
                Console.WriteLine("请输入你的选择");
                Console.ForegroundColor = ConsoleColor.Green;
                string input = Console.ReadLine();
                switch (input)
                {
                    case "1":
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("请输入联系人名字:");
                        Console.ForegroundColor = ConsoleColor.Green;
                        string name = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("请输入联系人手机号:");
                        Console.ForegroundColor = ConsoleColor.Green;
                        string tel = Console.ReadLine();
                        //判断手机号是否合法
                        bool b = Regex.IsMatch(tel, "^1[0-9]{10}$");
                        if (b)
                        {
                            ht.Add(name, tel);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine($"*******共有{ht.Count}个联系人***********");
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("您输入的手机号格式不对");
                        }

                        break;
                    case "2":
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("已添加的联系人有:");
                        foreach (var item in ht.Keys)
                        {
                            Console.Write(item + " ");
                        }
                        Console.WriteLine();
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("请输入您要查找的联系人姓名:");
                        Console.ForegroundColor = ConsoleColor.Green;
                        string nameFind = Console.ReadLine();
                        //获取这个联系人的电话
                        var telFind = ht[nameFind];
                        if (telFind == null)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("该联系人不存在");
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine($"你查找的联系人的电话是{telFind}");
                        }
                        break;
                    case "3":
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("已添加的联系人有:");
                        foreach (var item in ht.Keys)
                        {
                            Console.Write(item + " ");
                        }
                        Console.WriteLine();
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("请输入您想删除的联系人姓名:");
                        Console.ForegroundColor = ConsoleColor.Green;
                        string nameDel = Console.ReadLine();
                        if (ht.ContainsKey(nameDel))
                        {
                            Console.ForegroundColor = ConsoleColor.Cyan;
                            Console.WriteLine("您确定要删除吗,如果确定,请输入:y");
                            Console.ForegroundColor = ConsoleColor.Green;
                            string enterDel = Console.ReadLine();
                            if (enterDel.Equals("y", StringComparison.OrdinalIgnoreCase))
                            {
                                ht.Remove(nameDel);
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine("删除成功!");
                            }
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("对不起没有您要找的联系人");
                        }
                        break;
                    case "4":
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("已添加的联系人有:");
                        foreach (var item in ht.Keys)
                        {
                            Console.Write(item + " ");
                        }
                        Console.WriteLine();
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("请输入您想修改的联系人姓名:");
                        Console.ForegroundColor = ConsoleColor.Green;
                        string nameChange = Console.ReadLine();
                        //获取这个联系人的电话
                        var telChange = ht[nameChange];
                        if (telChange == null)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("该联系人不存在");
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Cyan;
                            Console.WriteLine($"{nameChange}的手机号是{telChange},请输入新的手机号:");
                            Console.ForegroundColor = ConsoleColor.Green;
                            string telNew = Console.ReadLine();
                            if (Regex.IsMatch(telNew, "^1[0-9]{10}$"))
                            {
                                ht[nameChange] = telNew;
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine("修改成功!");
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("您输入的手机号格式不对");
                            }


                        }
                        break;

                }
            }
            Console.ReadKey();

        }
    }
}

 IComparable泛型接口排序:

using System;
using System.Collections.Generic;

namespace ConsoleApp1        //IComparable泛型接口排序
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person(1, "贾宝玉", 16);
            Person p2 = new Person(2, "林黛玉", 14);
            Person p3 = new Person(3, "薛宝钗", 15);
            Person P4 = new Person(4, "史湘云", 16);
            //创建泛型集合
            List<Person> list = new List<Person>() { p1, p2, p3, P4 };
            Console.WriteLine("排序前:");
            foreach (var per in list)
            {
                Console.WriteLine($"姓名{per.Name},年龄{per.Age}");
            }
            list.Sort();
            Console.WriteLine("排序后:");
            foreach (var per in list)
            {
                Console.WriteLine($"姓名{per.Name},年龄{per.Age}");
            }

            Console.ReadKey();
        }
    }

    public class Person : IComparable<Person>
    {
        public Person(int id, string name, int age)
        {
            this.Name = name;
            this.Id = id;
            this.Age = age;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public int CompareTo(Person other)
        {
            return this.Age.CompareTo(other.Age);
        }
    }
}

IComparable接口实现排序: 

using System;
using System.Collections.Generic;

namespace ConsoleApp1        //IComparable接口实现排序
{
    class Program
    {
        static void Main(string[] args)
        {
            //List<string> list = new List<string>() {  "啊林黛玉", "比王熙凤","低贾宝玉" };
            //Console.WriteLine("排序前:");
            //foreach (string str in list)
            //{
            //    Console.WriteLine(str);
            //}
            //list.Sort();
            //Console.WriteLine("排序后:");
            //foreach (string str in list)
            //{
            //    Console.WriteLine(str);
            //}

            Person p1 = new Person(1, "贾宝玉", 16);
            Person p2 = new Person(2, "林黛玉", 14);
            Person p3 = new Person(3, "薛宝钗", 15);
            Person P4 = new Person(4, "史湘云", 16);
            //创建泛型集合
            List<Person> list = new List<Person>() { p1, p2, p3, P4 };
            Console.WriteLine("排序前:");
            foreach (var per in list)
            {
                Console.WriteLine($"姓名{per.Name},年龄{per.Age}");
            }
            list.Sort();
            Console.WriteLine("排序后:");
            foreach (var per in list)
            {
                Console.WriteLine($"姓名{per.Name},年龄{per.Age}");
            }

            Console.ReadKey();
        }
    }

    public class Person : IComparable
    {
        public Person(int id, string name, int age)
        {
            this.Name = name;
            this.Id = id;
            this.Age = age;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        //实现接口方法
        public int CompareTo(object obj)
        {
            //把obj转换成Person类型的对象,如果转换失败,则是Null
            Person per = obj as Person;
            //把当前对象的name成员和接受的参数的name成员进行比较,返回结果
            // 返回类型是int类型,返回大于0 表示,当前对象大于per,小于,则相反
            return this.Name.CompareTo(per.Name);
        }
    }
}

 

 IComparer泛型接口排序:

using System;
using System.Collections.Generic;

namespace ConsoleApp1        //IComparer泛型接口排序
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person(1, "贾宝玉", 16);
            Person p2 = new Person(2, "林黛玉", 14);
            Person p3 = new Person(3, "薛宝钗", 15);
            Person P4 = new Person(4, "史湘云", 16);
            //创建泛型集合
            List<Person> list = new List<Person>() { p1, p2, p3, P4 };
            Console.WriteLine("排序前:");
            foreach (var per in list)
            {
                Console.WriteLine($"姓名{per.Name},年龄{per.Age}");
            }

            Console.WriteLine("请选择:1.按姓名排序  2.按年龄排序");
            string select = Console.ReadLine();
            switch (select)
            {
                case "1":
                    list.Sort(new NameSort());
                    break;
                case "2":
                    list.Sort(new AgeSort());
                    break;
            }

            Console.WriteLine("排序后:");
            foreach (var per in list)
            {
                Console.WriteLine($"姓名{per.Name},年龄{per.Age}");
            }

            Console.ReadKey();
        }
    }

    public class Person
    {
        public Person(int id, string name, int age)
        {
            this.Name = name;
            this.Id = id;
            this.Age = age;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    //按姓名排序
    public class NameSort : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

    //按年龄排序
    public class AgeSort : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x.Age.CompareTo(y.Age);
        }
    }
}

List泛型集合: 

using System;
using System.Collections.Generic;

namespace ConsoleApp1        //List泛型集合
{
    /*
     * 泛型集合就是明确指定了要放入集合的对象是何种类型的集合
     * 
     */
    class Program
    {
        static void Main(string[] args)
        {
            //创建List泛型集合的对象
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(2);
            list.Add(3);
            list.AddRange(new int[] { 4, 5, 6 });
            list.AddRange(list);

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            Console.ReadKey();
        }
    }
}

 List泛型集合练习:

using System;
using System.Collections.Generic;

namespace ConsoleApp1        //List泛型集合练习
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = new Student(1, "曹凯军");
            Student stu2 = new Student(2, "何帅");
            Student stu3 = new Student(3, "李琴琴");
            //集合初始化器
            List<Student> students = new List<Student>() { stu1, stu2, stu3 };
            //foreach (Student item in students)
            //{
            //    Console.WriteLine(item.Say());
            //}
            //ForEach()方法结合lambda表达式实现循环遍历
            // students.ForEach(s=>Console.WriteLine(s.Say()));

            //FindAll方法检索条件匹配所有元素
            List<Student> _students = students.FindAll(m => m.Id < 2);
            _students.ForEach(s => Console.WriteLine(s.Say()));

            Console.ReadKey();

        }
    }

    public class Student
    {
        //private int id;
        //public int Id
        //{
        //    get { return id; }
        //    set { id = value; }
        //}

        public Student(int id, string name)
        {
            this.Id = id;
            this.Name = name;
        }
        //自动属性
        public int Id { get; set; }
        public string Name { get; set; }

        public string Say()
        {
            return "姓名:" + Name + ",学号:" + Id;
        }
    }
}

 var隐式类型:

using System;

namespace ConsoleApp1        //var隐式类型
{
    class Program
    {
        static void Main(string[] args)
        {
            //int i = 1;
            //string s = "张三";
            var i = 2;
            var str = "李四";
            Console.WriteLine(i.GetType());
            Console.WriteLine(str.GetType());
            Console.ReadKey();
        }
    }
}

 泛型集合常用的扩展方法:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1        //泛型集合常用的扩展方法
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person(1, "贾宝玉");
            Person p2 = new Person(2, "林黛玉");
            Person p3 = new Person(3, "薛宝钗");
            Person P4 = new Person(4, "史湘云");
            //创建泛型集合
            List<Person> persons = new List<Person>() { p1, p2, p3, P4 };
            //获取泛型集合中第一个元素,如果没有,则返回null
            //需引用System.Linq命名空间
            Person per1 = persons.FirstOrDefault();
            Console.WriteLine($"泛型集合中第一个元素的名字是{per1.Name}");
            //判断泛型集合中是不是所有的元素ID小于3,如果是返回true
            bool b = persons.All(s => s.Id > 0);
            Console.WriteLine(b);
            //通过where()扩展方法,过滤id<3的person对象,Count就是符合条件的对象个数
            int perCount = persons.Where(s => s.Id < 3).Count();
            Console.WriteLine(perCount);

            Console.ReadKey();
        }
    }

    public class Person
    {
        public Person(int id, string name)
        {
            this.Name = name;
            this.Id = id;
        }
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

 字典泛型集合:

using System;
using System.Collections.Generic;

namespace ConsoleApp1        //字典泛型集合
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "曹凯军");
            dic.Add(2, "何帅");
            dic.Add(3, "李琴琴");
            //foreach (var item in dic.Keys)
            //{
            //    Console.WriteLine("{0}=========>{1}",item,dic[item]);
            //}
            foreach (KeyValuePair<int, string> kv in dic)
            {
                Console.WriteLine("{0}=>{1}", kv.Key, kv.Value);
            }
            Console.ReadKey();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鹰@四海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值