ConcurrentDictionary数据结构的使用方法

ConcurrentDictionary数据结构是4.0之后才加进去的,次数据结构最大的有点就是线程安全的

 

编码实现using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Concurrent;

namespace 字典排序测试
{
    public partial class Form1 : Form
    {
        ConcurrentDictionary<int, int> dic = new ConcurrentDictionary<int, int>();
        public Form1()
        {
            InitializeComponent();

            dic.TryAdd(1, 9);
            dic.TryAdd(2, 2);
            dic.TryAdd(3, 3);
            dic.TryAdd(4, 4);
            dic.TryAdd(5, 5);
            dic.TryAdd(6, 6);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            int j = 0;
            //foreach (KeyValuePair<int, int> kvp in dic)
            //{

            //    listBox1.Items.Add(j.ToString()+": "+kvp.Key + "," + kvp.Value);
            //    j++;

            //}

            for (int i = 0; i < dic.Count; i++)
            {
                var item = dic.ElementAt(i);
                listBox1.Items.Add(j.ToString() + ": " + item.Key + "," + item.Value);
                j++;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            int i=0;
            if (dic.TryRemove(Convert.ToInt32(textBox1.Text), out i))
            {
                MessageBox.Show("remove ok");
            }
            listBox1.Items.Clear();
            button1_Click(null, null);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dic.TryAdd(Convert.ToInt32(textBox2.Text), Convert.ToInt32(textBox3.Text)))
            {
                MessageBox.Show("TryAdd ok");
            }
            listBox1.Items.Clear();
            button1_Click(null, null);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Array arr = dic.ToArray();
            //1.按照X排序:OrderBy升序,OrderByDescending降序
            var temp=dic.OrderBy((kv => kv.Value));
            //.取值Max,Min,last最后一个元素,sum,take从序列的开头返回指定数量的连续元素,
            //其他参考 http://msdn.microsoft.com/zh-cn/library/dd287191.aspx
            int max = dic.Max(kv => kv.Value);
            //
            List<int> l = temp.Select(kv => kv.Key).ToList();

            listBox1.Items.Clear();
            foreach (var item in l)
                listBox1.Items.Add(item.ToString());

        }
    }
}


转载于:https://www.cnblogs.com/sung/archive/2013/01/14/2859801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值