C#泛型集合类介绍之List<T>(转载+编辑)

集合类是程序设计中最常用到的类型之一(另外一个是string)

最常用的集合类是List<T>和Dictionary<TKey, TValue>这2个。

List<T>常用来表示一类集合对象,比如一个班级里的全部学生或待排序的若干个数字,前者可以用List<Student>来表示,后者可以用List<int>来表示。

泛型集合类前面的泛型2字的含义可以理解为集合内保存的类型可以是泛泛的类型,不特定于某种类型,那这种集合类的用途就大了,它既可以表示基本类型的集合,也可以表示我们自定义的任何类型的集合。

    怎样创建泛型集合?

    主要利用System.Collections.Generic命名空间下面的List<T>泛型类创建集合,语法如下:

定义Person类如下:

   可以看到,泛型集合大大简化了集合的实现代码,通过它,可以轻松创建指定类型的集合。非但如此,泛型集合还提供了更加强大的功能,下面看看其中的排序及搜索。

List<T> ListOfT = new List<T>();

其中的"T"就是所要使用的类型,既可以是简单类型,如string、int,也可以是用户自定义类型。下面看一个具体例子。

 

class Person

{

    private string _name; //姓名

    private int _age; //年龄

    //创建Person对象

    public Person(string Name, int Age)

    {

        this._name= Name;

        this._age = Age;

    }

    //姓名

    public string Name

    {

        get { return _name; }

    }

    //年龄

    public int Age

    {

        get { return _age; }

    }

}

//创建Person对象

Person p1 = new Person("张三", 30);

Person p2 = new Person("李四", 20);

Person p3 = new Person("王五", 50);

//创建类型为Person的对象集合

List<Person> persons = new List<Person>();

//将Person对象放入集合

persons.Add(p1);

persons.Add(p2);

persons.Add(p3);

//输出第2个人的姓名

Console.Write(persons[1].Name);

List的方法和属性 方法或属性 作用

Capacity 用于获取或设置List可容纳元素的数量。当数量超过容量时,这个值会自动增长。您可以设置这个值以减少容量,也可以调用trin()方法来减少容量以适合实际的元素数目。

Count 属性,用于获取数组中当前元素数量

Item( ) 通过指定索引获取或设置元素。对于List类来说,它是一个索引器。

Add( ) 在List中添加一个对象的公有方法

AddRange( ) 公有方法,在List尾部添加实现了ICollection接口的多个元素

BinarySearch( ) 重载的公有方法,用于在排序的List内使用二分查找来定位指定元素.

Clear( ) 在List内移除所有元素

Contains( ) 测试一个元素是否在List内

CopyTo( ) 重载的公有方法,把一个List拷贝到一维数组内

Exists( ) 测试一个元素是否在List内

Find( ) 查找并返回List内的出现的第一个匹配元素

FindAll( ) 查找并返回List内的所有匹配元素

GetEnumerator( ) 重载的公有方法,返回一个用于迭代List的枚举器

Getrange( ) 拷贝指定范围的元素到新的List内

IndexOf( ) 重载的公有方法,查找并返回每一个匹配元素的索引

Insert( ) 在List内插入一个元素

InsertRange( ) 在List内插入一组元素

LastIndexOf( ) 重载的公有方法,,查找并返回最后一个匹配元素的索引

Remove( ) 移除与指定元素匹配的第一个元素

RemoveAt( ) 移除指定索引的元素

RemoveRange( ) 移除指定范围的元素

Reverse( ) 反转List内元素的顺序

Sort( ) 对List内的元素进行排序

ToArray( ) 把List内的元素拷贝到一个新的数组内

trimToSize( ) 将容量设置为List中元素的实际数目

这些方法,我们将在以后的实践中用到其中的一些,到时候相信会有更多的体会。这些List的方法我们掌握的越牢固越好;否则,假设你不知道List<string>类已经提供了Contains方法的话,再自己写一个检查集合中是否存在某元素的方法的话,就浪费时间了。对于其他.NET提供的类型也是如此,了解的越多,可能就越加运用自如,而这些需要不断的多读,多写代码。

 

看一个实例:定义一个员工的集合,对员工集合内的元素进行查询和删除。

首先是员工类:

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

namespace StringTest
{
    class Employee
    {



        private int id;

        public int ID
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string sex;

        public string Sex
        {
            get { return sex; }
            set { sex = value; }
        }
        private int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        // A:实现新增员工(工号,年龄,姓名,性别)  

        public Employee(int _id, int _age, string _name, string _sex)
        {
            this.Name = _name;
            this.Age = _age;
            this.Sex = _sex;
            this.ID = _id;
        }


        //B:展示员工信息, 

        public void ShowMsg()
        {

            Console.WriteLine("工号:{0} 年龄:{1} 姓名:{2} 性别:{3}", this.ID, this.Age, this.Name, this.Sex);
        }
    }
}
View Code

  接下来是公司类(公司类维护一个公司全部员工的集合(用List<Employee>表达)):

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

namespace StringTest
{
    class Company
    {
        public List<Employee> list = new List<Employee>();
        //public Dictionary<string, List<KaoqinRecord>> dicKaoQinEachDay = new Dictionary<string, List<KaoqinRecord>>();
        public void AddEmp(Employee sc)
        {
            list.Add(sc);
        }

        public void DelEmp(int nID)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].ID == nID)
                {
                    list.RemoveAt(i);
                }
            }
        }

        public void PrintAllEmp()
        {
            for (int i = 0; i < list.Count; i++)
            {
                list[i].ShowMsg();
            }

        }

        public Employee FindEmp(int nID)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].ID == nID)
                {
                    return list[i];
                }
            }
            return null;
        }
    }
}
View Code

  最后是主方法:

class Program
    {
        static Company c = new Company();
        static void Main(string[] args)
        {
            ////  1、使用你所学的C#的容器类实现员工考勤信息管理, 
            //实现以下功能:要求:使用泛型集合list的添加,查询和删除操作) 
            // A:实现新增员工(工号,年龄,姓名,性别)
            List<Employee> list = new List<Employee>();
    

            c.AddEmp(new Employee(11, 18, "zhang3", ""));
            c.AddEmp(new Employee(22, 28, "li4", ""));
            c.AddEmp(new Employee(33, 38, "wang5", ""));
            c.AddEmp(new Employee(44, 48, "zhao6", ""));
            c.AddEmp(new Employee(55, 58, "qian7", ""));
            c.AddEmp(new Employee(66, 68, "sun8", ""));


            c.PrintAllEmp();
           

            //C:根据工号删除员工信息


             Console.WriteLine("请输入删除员工信息!工号:");
            int numDel = Convert.ToInt32(Console.ReadLine());


            c.DelEmp(numDel);

            c.PrintAllEmp();

            //D根据员工工号查询员工信息 
            Console.WriteLine("请输入查询员工信息!工号:");
            int numShu = Convert.ToInt32(Console.ReadLine());

            Employee sc = c.FindEmp(numShu);
            sc.ShowMsg();
    }
}
View Code

 

 

posted @ 2013-02-17 22:34  际为软件事务所  阅读(1547)  评论(0编辑  收藏  举报