code_junkie

Literal hashes in c#?

Nov 10th, 2011
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. { "whatever" => {i => 1}; "and then something else" => {j => 2}};
  2.  
  3. var students = new Dictionary<int, StudentName>()
  4. {
  5. { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
  6. { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},
  7. { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}
  8. };
  9.  
  10. public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data)
  11. {
  12. Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2));
  13. if (data == null || data.Length == 0) return dict;
  14.  
  15. KeyType key = default(KeyType);
  16. ValueType value = default(ValueType);
  17.  
  18. for (int i = 0; i < data.Length; i++)
  19. {
  20. if (i % 2 == 0)
  21. key = (KeyType) data[i];
  22. else
  23. {
  24. value = (ValueType) data[i];
  25. dict.Add(key, value);
  26. }
  27. }
  28.  
  29. return dict;
  30. }
  31.  
  32. IDictionary<string,object> myDictionary = Dict<string,object>(
  33. "foo", 50,
  34. "bar", 100
  35. );
  36.  
  37. using System;
  38. using System.Collections.Generic;
  39. using System.Linq;
  40. using System.Text;
  41.  
  42. namespace Dictionary
  43. {
  44. class Program
  45. {
  46. static void Main(string[] args)
  47. {
  48. Program p = new Program();
  49. Dictionary<object, object > d = p.Dic<object, object>("Age",32,"Height",177,"wrest",36);//(un)comment
  50. //Dictionary<object, object> d = p.Dic<object, object>();//(un)comment
  51.  
  52. foreach(object o in d)
  53. {
  54. Console.WriteLine(" {0}",o.ToString());
  55. }
  56. Console.ReadLine();
  57. }
  58.  
  59. public Dictionary<K, V> Dic<K, V>(params object[] data)
  60. {
  61. //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null;
  62. if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary<K,V>(1){{ (K)new Object(), (V)new object()}};
  63.  
  64. Dictionary<K, V> dc = new Dictionary<K, V>(data.Length / 2);
  65. int i = 0;
  66. while (i < data.Length)
  67. {
  68. dc.Add((K)data[i], (V)data[++i]);
  69. i++;
  70. }
  71. return dc;
  72. }
  73. }
  74. }
Add Comment
Please, Sign In to add comment