Guest User

Untitled

a guest
Jul 20th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. public void IncrementCount(Dictionary<int, int> someDictionary, int id)
  2. {
  3. int currentCount;
  4. if (someDictionary.TryGetValue(id, out currentCount))
  5. {
  6. someDictionary[id] = currentCount + 1;
  7. }
  8. else
  9. {
  10. someDictionary[id] = 1;
  11. }
  12. }
  13.  
  14. someDictionary.AddOrUpdate(id, 1, (id, count) => count + 1);
  15.  
  16. public void IncrementCount(Dictionary<int, int> someDictionary, int id)
  17. {
  18. if (!someDictionary.ContainsKey(id))
  19. someDictionary[id] = 0;
  20.  
  21. someDictionary[id]++;
  22. }
  23.  
  24. int currentCount;
  25.  
  26. // currentCount will be zero if the key id doesn't exist..
  27. someDictionary.TryGetValue(id, out currentCount);
  28.  
  29. someDictionary[id] = currentCount + 1;
  30.  
  31. public static void Increment<T>(this Dictionary<T, int> dictionary, T key)
  32. {
  33. int count;
  34. dictionary.TryGetValue(key, out count);
  35. dictionary[key] = count + 1;
  36. }
  37.  
  38. var dictionary = new Dictionary<string, int>();
  39. dictionary.Increment("hello");
  40. dictionary.Increment("hello");
  41. dictionary.Increment("world");
  42.  
  43. Assert.AreEqual(2, dictionary["hello"]);
  44. Assert.AreEqual(1, dictionary["world"]);
Add Comment
Please, Sign In to add comment