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());

        }
    }
}


相关文章:

  • 2022-12-23
  • 2021-06-04
  • 2021-04-04
  • 2022-03-07
  • 2022-12-23
  • 2021-12-15
  • 2021-09-28
  • 2021-12-15
猜你喜欢
  • 2022-12-23
  • 2022-03-03
  • 2021-08-08
  • 2021-04-02
  • 2021-10-25
  • 2021-08-27
  • 2022-12-23
相关资源
相似解决方案