用到索引器创建一个集合DEMO

来源:互联网 发布:dijkstra算法 c语言 编辑:程序博客网 时间:2024/05/16 23:46

  前一段时间研究了一下LINQ,上一篇博客讲解了一下C#中的索引器,正好有一个例子包含了这两者的知识,今天就给大家展示一下这个DEMO,在这个DEMO中加深对索引器的理解

  我们再来回顾一下LINQ的作用,它的主要用途是对数据源进行查询,而最常见的一种数据源是集合,其实他就是内存中的一个对象,例如数组、列表list等可以称为集合。

  而linq全称为语言继承查询,所以在LINQ家族中,不论底层的数据源如何,对于应用程序而言,使用的都是统一的LINQ查询方式。

  这一篇中我们先创建一个集合,在以后的博客中在介绍如何使用LINQ对集合进行查询,这一篇的重点还有一个就是体会索引器的应用

首先介绍一下集合的特点:
1. 可以通过索引或键来访问集合的成员,例如collection[index]
2. 可以使用for,foreach遍历
3. 具有属性或方法,用于获得集合中的成员数量,常见的有count属性
4. 拥有一些添加、移除成员的方法:add、insert、remove、clear等

一、首先创建产品的类Product

下边采用测试驱动开发的方法,先写好测试用例,然后再去实现它。

    public class Product {        public int Id { get; set; }        public string Name { get; set; }        public string Code { get; set; }        public string Category { get; set; }        public decimal Price { get; set; }        public DateTime ProduceDate { get; set; }        //美化输出格式        public override string ToString()        {   //padleft:在字符串左边补足            return String.Format("{0}{1}{2}{3}{4}{5}",this.Id.ToString().PadLeft(2)                ,this.Category.PadLeft(15),this.Code.PadLeft(7),this.Name.PadLeft(17),                this.Price.ToString ().PadLeft (8),this.ProduceDate                .ToString("yyyy-M-d").PadLeft(13));        }        /// <summary>        /// 获取一个产品集合,仅作为演示,用于填充并返回一个ProductCollection集合        /// </summary>        /// <returns></returns>        public static ProductCollection GetSampleCollection(){            ProductCollection collection=new ProductCollection(            new Product {Id=1,Code="1001",Category="Red Wine",Name="Torres Coronas",Price=285.5m,                ProduceDate=DateTime.Parse("1997-12-8")},            new Product{Id=3,Code="2001",Category="White Spirit",Name="Mao Tai",Price=1680m,                ProduceDate=DateTime.Parse("2001-5-8")},            new Product {Id=4,Code="2013",Category="White Spirit",Name="Wu Liang Ye",Price=1260m,                ProduceDate=DateTime.Parse("2005-12-8")},            new Product{Id=8,Code="3001",Category="Beer",Name="TSINGTAO",Price=6.5m,                ProduceDate=DateTime.Parse("2012-4-8")},            new Product {Id=11,Code="1003",Category="Red Wine",Name="BorieNoaillan",Price=468m,                ProduceDate=DateTime.Parse("1995-7-6")},            new Product{Id=15,Code="1007",Category="Red Wine",Name="Point Noir Rose",Price=710m,                ProduceDate=DateTime.Parse("2088-9-18")},            new Product{Id=17,Code="3009",Category="Beer",Name="Kingway",Price=5.5m,                ProduceDate=DateTime.Parse("2012-6-13")});            return collection;        }    }


二、ProductCollection(这里用到了C#索引器)

 //创建一个Product集合类型        //在内部包含一个泛型类List<Product>        //然后将所有关于集合的操作都委托给这个List<Product>执行        //ProductCollection仅仅相当于一个包装器(wrapper)        public class ProductCollection{            private Hashtable table;            //构造函数:            public ProductCollection(){                table =new Hashtable();            }            public ProductCollection(params Product[] array){                table=new Hashtable();                foreach(Product item in array){                    this.Add(item);                }            }            public ICollection Keys {                get { return table.Keys; }            }            private string getKeys(int index) {                if (index < 0 || index > table.Keys.Count)                    throw new Exception("索引超出范围");                string selected = "";                int i = 0;                foreach (string key in table.Keys)                {                    if (i==index)                    {                        selected = key;                        break;                    }                    i++;                }                return selected;            }            //索引器的应用,可以支持collection[index]的访问            public Product this[int index] {                get {                    string key = getKeys(index);                    return table[key] as Product;                }                set {                    string key = getKeys(index);                    table[key] = value;                }            }            private string getKey(string key) {                foreach (string k  in table.Keys)                {                    if (key==k)                    {                        return key;                    }                }                throw new Exception("不存在此键值");            }            public Product this[string key] {                get {                    string selected = getKey(key);                    return table[selected] as Product;                }                set {                    string selected = getKey(key);                    table.Remove(table[selected]);                    this.Add(value);                }            }            public void Add(Product item) {                 //确保key不能重复                foreach (string key in table.Keys)                {                    if (key==item.Code)                    {                        throw new Exception("产品代码不能重复");                    }                }                table.Add(item.Code, item);            }            //下边的三个方法,没有写具体的实现            public void Insert(int index,Product item){}            public bool Remove(Product item){                return true;            }            public bool RemoveAt(int index){                return true;            }            //清除全部成员            public void Clear(){                table=new Hashtable();            }            public int Count{                get{return table.Keys.Count;}            }            //private List<Product> list=new List<Product>();            //索引器,以支持类似于collection[index]            //public Product this[int index]{get;set;}            //索引器,以支持类似于collection[key]这样的访问            //public Product this[string key]{get;set;}            //在末尾添加成员            //public void Add(Product item){}        }


三、客户端访问

static void Main(string[] args)        {            ProductCollection col = Product.GetSampleCollection();            foreach (string key  in col.Keys )            {                string line = col[key].ToString();                Console.WriteLine(line);            }            Console.ReadLine();        }

这里写图片描述


总结

客户端的作用就是将集合中的内容按照index顺序打印输出到屏幕,索引器应用于集合的创建当中比较做,简化了编程人员的编码工作~!

P.S.DEMO参考了《.NET之美》

0 0
原创粉丝点击