标签:
如果Value是引用,那么在使用Value.Clear()的时候。会清空Value的所有元素,但是不会改变Value的引用
private static void Main() { try { var concurrentDictionary = new ConcurrentDictionary<string, List<int>>(); concurrentDictionary.TryAdd("chuck", new List<int>() {1, 2, 3}); concurrentDictionary.TryAdd("lihu", new List<int>() {4, 5, 6}); var dictionary = concurrentDictionary.ToDictionary(x => x.Key, x => x.Value); foreach (var list in concurrentDictionary.Values) { list.Clear(); } foreach (var name in dictionary.Keys) { Console.WriteLine(name); var list = dictionary[name]; foreach (var number in list) { Console.Write("\t{0}",number); } Console.WriteLine(); } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); }
还需要测试下Value是List<Student>的情况
internal class Student { internal int Id { get; set; } internal string Name { get; set; } } internal class Program { private static void Main() { try { var concurrentDictionary = new ConcurrentDictionary<string, Student>(); concurrentDictionary.TryAdd("chuck", new Student() {Id = 1, Name = "chuck"}); concurrentDictionary.TryAdd("lihu", new Student() {Id = 2, Name = "lihu"}); var dictionary = concurrentDictionary.ToDictionary(x => x.Key, x => x.Value); foreach (var key in concurrentDictionary.Keys) { concurrentDictionary[key].Id = 0; concurrentDictionary[key].Name = "hello world"; } foreach (var name in dictionary.Keys) { Console.Write(name); Console.Write("\tid={0}\tname={1}", dictionary[name].Id, dictionary[name].Name); Console.WriteLine(); } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); } }
Value是值类型的
private static void Main() { try { var concurrentDictionary = new ConcurrentDictionary<string, int>(); concurrentDictionary.TryAdd("chuck", 1); concurrentDictionary.TryAdd("lihu",4); var dictionary = concurrentDictionary.ToDictionary(x => x.Key, x => x.Value); foreach (var key in concurrentDictionary.Keys) { concurrentDictionary[key] = 0; } foreach (var name in dictionary.Keys) { Console.Write(name); Console.Write("\t{0}", dictionary[name]); Console.WriteLine(); } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); }
ConcurrentDictionary的ToDictionary
标签:
原文地址:http://www.cnblogs.com/chucklu/p/4943173.html