您的位置:首页 > 理论基础 > 数据结构算法

ConcurrentDictionary数据结构的使用方法

2013-01-14 15:32 92 查看
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());

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: