Dictionary<TKey, TValue>集合类


            Dictionary<string, string> myDic = new Dictionary<string, string>();
            myDic.Add("aaa", "111");
            myDic.Add("bbb", "222");
            myDic.Add("ccc", "333");
            myDic.Add("ddd", "444");
            //如果添加已经存在的键,add方法会抛出异常 
            try
            {
                myDic.Add("ddd", "ddd");
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("此键已经存在:" + ex.Message);
            }
            //解决add()异常的方法是用ContainsKey()方法来判断键是否存在 
            if (!myDic.ContainsKey("ddd"))
            {
                myDic.Add("ddd", "ddd");
            }
            else
            {
                Console.WriteLine("此键已经存在:");

            }

            //而使用索引器来负值时,如果建已经存在,就会修改已有的键的键值,而不会抛出异常 
            myDic["ddd"] = "ddd";
            myDic["eee"] = "555";

            //使用索引器来取值时,如果键不存在就会引发异常 
            try
            {
                Console.WriteLine("不存在的键\"fff\"的键值为:" + myDic["fff"]);
            }
            catch (KeyNotFoundException ex)
            {
                Console.WriteLine("没有找到键引发异常:" + ex.Message);
            }
            //解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值 
            string value = "";
            if (myDic.TryGetValue("fff", out value))
            {
                Console.WriteLine("不存在的键\"fff\"的键值为:" + value);
            }
            else
            {
                Console.WriteLine("没有找到对应键的键值");
            }

            //下面用foreach 来遍历键值对 
            //泛型结构体用来存储健值对 
            foreach (KeyValuePair<string, string> kvp in myDic)
            {
                Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
            }
            //获取值得集合 
            foreach (string s in myDic.Values)
            {
                Console.WriteLine("value={0}", s);
            }
            //获取值得另一种方式 
            Dictionary<string, string>.ValueCollection values = myDic.Values;
            foreach (string s in values)
            {
                Console.WriteLine("value={0}", s);
            } 


http://www.cnblogs.com/moss_tan_jun/archive/2010/09/20/1831867.html


Dictionary<TKey, TValue>集合类 购物车应用:

    public class CartBLL : ICartBLL
    {
        private Dictionary<string, CartInfo> cartItems = new Dictionary<string, CartInfo>();

        #region ICartBLL 成员

        public void Clear()
        {
            cartItems.Clear();
        }

        public void Remove(string itemId)
        {
            cartItems.Remove(itemId);
        }

        public void Add(CartInfo item)
        {
            CartInfo cartItem;
            if (!cartItems.TryGetValue(item.ItemId, out cartItem))
                cartItems.Add(item.ItemId, item);
            else
                cartItem.Quantity += item.Quantity;
        }

        public void SetQuantity(string itemId, int qty)
        {
            cartItems[itemId].Quantity = qty;
        }

        public CartInfo GetCartInfo(TbProduct p)
        {
            CartInfo cartInfo = new CartInfo()
            {
                Quantity = p.PQuantity,
                ProductName = p.p_name,
                ProductId = p.id.ToString(),
                Price = p.p_m_price,
                ItemId = p.id.ToString(),
                Image = p.p_smallpic
            };
            return cartInfo;
        }

        public ICollection<CartInfo> CartItems
        {
            get { return cartItems.Values; }
        }

        public int Count
        {
            get { return cartItems.Count; }
        }

        public decimal Total
        {
            get
            {
                decimal total = 0;
                foreach (CartInfo item in cartItems.Values)
                    total += item.Price * item.Quantity;
                return total;
            }
        }

        #endregion
    }

    interface ICartBLL
    {
        void Clear();//清除所有购物车
        void Remove(string itemId);//清除购物车
        void Add(CartInfo item);//添加购物车
        void SetQuantity(string itemId, int qty);//更改购物车数量
        CartInfo GetCartInfo(TbProduct p);//
        ICollection<CartInfo> CartItems { get; }//获取购物车列表
        int Count { get; }//获取购物车数量
        decimal Total { get; }//获取购物车总价钱
    }

    /// <summary>
    /// 购物车
    /// </summary>
    [Serializable]
    public class CartInfo
    {
        private int quantity;

        public int Quantity
        {
            get { return quantity; }
            set { quantity = value; }
        }
        private decimal price;

        public decimal Price
        {
            get { return price; }
            set { price = value; }
        }
        private string productName;

        public string ProductName
        {
            get { return productName; }
            set { productName = value; }
        }
        private string productId;

        public string ProductId
        {
            get { return productId; }
            set { productId = value; }
        }

        private string itemId;
        public string ItemId
        {
            get { return itemId; }
            set { itemId = value; }
        }
        private string image;

        public string Image
        {
            get { return image; }
            set { image = value; }
        }
    }

       [Serializable]
        public partial class TbProduct
	{
        public TbProduct(){}
	#region Model
	private int _id;	
	private string _p_name;
        private decimal _p_m_price;
        private decimal _p_price;
	private string _p_smallpic;

        private int pQuantity;

        public int PQuantity
        {
            get { return pQuantity; }
            set { pQuantity = value; }
        }
		/// <summary>
		/// 
		/// </summary>
		public int id
		{
			set{ _id=value;}
			get{return _id;}
		}
		/// <summary>
		/// 
		/// </summary>
		public string p_name
		{
			set{ _p_name=value;}
			get{return _p_name;}
		}
		/// <summary>
		/// 
		/// </summary>
        public decimal p_m_price
		{
			set{ _p_m_price=value;}
			get{return _p_m_price;}
		}
		/// <summary>
		/// 
		/// </summary>
		public decimal p_price
		{
			set{ _p_price=value;}
			get{return _p_price;}
		}
		
		/// <summary>
		/// 
		/// </summary>
		public string p_smallpic
		{
			set{ _p_smallpic=value;}
			get{return _p_smallpic;}
		}
		
		#endregion Model

	}


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

namespace ShoppingCartApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CartBLL cart = new CartBLL();
            TbProduct p1 = new TbProduct()
            {
                id = 1,
                p_name = "产品1",
                p_m_price = 50,
                PQuantity = 1,
                p_smallpic = "pic1"
            };
            TbProduct p2 = new TbProduct()
            {
                id = 2,
                p_name = "产品2",
                p_m_price = 30,
                PQuantity = 1,
                p_smallpic = "pic2"
            };
            cart.Add(cart.GetCartInfo(p1));
            cart.Add(cart.GetCartInfo(p2));

            displayResult(cart.CartItems, cart);//显示结果

            Console.WriteLine("重复添加2个编号为1的产品");
            cart.Add(cart.GetCartInfo(p1));
            cart.Add(cart.GetCartInfo(p1));
            displayResult(cart.CartItems, cart);//显示结果

            Console.WriteLine("删除编号为2的产品");
            cart.Remove("2");
            displayResult(cart.CartItems, cart);//显示结果

            Console.WriteLine("更改编号为1的产品数量为5");
            cart.SetQuantity("1", 5);
            displayResult(cart.CartItems, cart);//显示结果

            Console.WriteLine("添加编号为3的产品");
            TbProduct p3 = new TbProduct()
            {
                id = 3,
                p_name = "产品3",
                p_m_price = 140,
                PQuantity = 1,
                p_smallpic = "pic3"
            };
            cart.Add(cart.GetCartInfo(p3));
            displayResult(cart.CartItems, cart);//显示结果

            Console.WriteLine("清空购物车");
            cart.Clear();
            displayResult(cart.CartItems, cart);//显示结果

            Console.ReadKey();
        }

        public static void displayResult(ICollection<CartInfo> values, CartBLL cart)
        {
            foreach (CartInfo s in values)
            {
                Console.WriteLine("编号={0},产品编号={1},产品名={2},价格={3},图片={4},数量={5},总价钱={6}", s.ItemId, s.ProductId, s.ProductName, s.Price, s.Image, s.Quantity, s.Quantity * s.Price);
            }
            Console.WriteLine("总价钱={0}", cart.Total);
            Console.WriteLine("======================");
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值