Guest User

Untitled

a guest
Jun 25th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. Dictionary<int, string> dic;
  2.  
  3. foreach(string s in dic.Values)
  4. {
  5. Console.WriteLine(s);
  6. }
  7.  
  8. foreach(KeyValuePair<int, string> kvp in dic)
  9. {
  10. Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
  11. }
  12.  
  13. foreach(int key in dic.Keys)
  14. {
  15. Console.WriteLine(key.ToString());
  16. }
  17.  
  18. Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" };
  19. foreach(KeyValuePair<int, string> kvp in newValues)
  20. {
  21. dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there
  22. }
  23.  
  24. List<int> keys = new List<int>() { 1, 3 };
  25. foreach(int key in keys)
  26. {
  27. dic.Remove(key);
  28. }
  29.  
  30. Dictionary<int,int> dic=new Dictionary<int, int>();
  31.  
  32. //...fill the dictionary
  33.  
  34. int[] keys = dic.Keys.ToArray();
  35. foreach (int i in keys)
  36. {
  37. dic.Remove(i);
  38. }
  39.  
  40. public static void MutateEach(this IDictionary<TKey, TValue> dict, Func<TKey, TValue, KeyValuePair<TKey, TValue>> mutator)
  41. {
  42. var removals = new List<TKey>();
  43. var additions = new List<KeyValuePair<TKey, TValue>>();
  44.  
  45. foreach (var pair in dict)
  46. {
  47. var newPair = mutator(pair.Key, pair.Value);
  48. if ((newPair.Key != pair.Key) || (newPair.Value != pair.Value))
  49. {
  50. removals.Add(pair.Key);
  51. additions.Add(newPair);
  52. }
  53. }
  54.  
  55. foreach (var removal in removals)
  56. dict.Remove(removal);
  57.  
  58. foreach (var addition in additions)
  59. dict.Add(addition.Key, addition.Value);
  60. }
  61.  
  62. myDict.MutateEach(key => key.ToLower(), value => value.Trim());
Add Comment
Please, Sign In to add comment