Advertisement
Guest User

useful nippets C# for advanced

a guest
Oct 8th, 2015
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.61 KB | None | 0 0
  1. print array in one line
  2. --------
  3. Console.WriteLine(string.Join(", ", arr));
  4. Console.WriteLine("[{0}]", string.Join(", ", arr));
  5. =================================================
  6. replace text using regex
  7. --------
  8. string text = Regex.Replace(sb.ToString(), @"\s+", " ");
  9. ==================================================
  10. string to int array
  11. --------
  12. int[] arr = Console.ReadLine().Split(' ').Select
  13.  
  14. (int.Parse).ToArray();
  15. ==================================================
  16. list all elements in array
  17. --------
  18. int[] arr = { 1 , 2 , 3 };
  19. arr.ToList().ForEach(a => Console.WriteLine(a));
  20. ==================================================
  21. find if a number is float/decimal/double or not
  22. --------
  23. if (item % 1 == 0)
  24. {
  25.     // it is not
  26. }
  27. else
  28. {
  29.     // it is
  30. }
  31. ==================================================
  32. Remove all numbers that are bigger then `n` in a list
  33. --------
  34. list.RemoveAll(p => p <= `n`);
  35. ==================================================
  36. Select and order by elements in list
  37. --------
  38. var results = list.Where(i => i % 2 == 0).OrderBy(p => p);
  39. ==================================================
  40. Print only half all elements in a list
  41. ---------
  42. list.ForEach(p => Console.WriteLine(p/2));
  43. ==================================================
  44. Split and remove all white spaces in a list
  45. ---------
  46. List<int> numsList = Console.ReadLine().Split(' ').Where(s
  47.  
  48. => !string.IsNullOrWhiteSpace(s)).Select(p => int.Parse
  49.  
  50. (p)).ToList();
  51. ==================================================
  52. Split string by multiple character delimiter (new char[]
  53.  
  54. {'.', '?'})
  55. ---------
  56. List<string> input = Console.ReadLine().Split(new string[]
  57.  
  58. { " ", "," },
  59.  
  60. StringSplitOptions.RemoveEmptyEntries).ToList();
  61. ==================================================
  62. Match collection !!!!
  63. ---------
  64. MatchCollection cleanData = Regex.Matches(input, pattern);
  65. foreach (Match match in cleanData)
  66. {
  67. Console.WriteLine("Area Code: {0}", match.Groups[1].Value);
  68. }
  69. ===================================================
  70. Split using regex
  71. ---------
  72. string pattern = @"\s+";
  73. string[] substrings = Regex.Split(input, pattern);
  74. ==================================================
  75. Replace using regex
  76. ---------
  77. string athlete = Regex.Replace(tokens[0].Trim(), @"\s+", "
  78.  
  79. ");
  80. ==================================================
  81. Sort ints Asc or Desc
  82. ---------
  83. li.Sort((a, b) => a.CompareTo(b)); // ascending sort
  84. li.Sort((a, b) => -1* a.CompareTo(b)); // descending sort
  85. ===================================================
  86. Sort by name and if the name is the same order by age
  87.  
  88. (OrderBy || OrderByDesending)
  89. ---------
  90. var pets = new [] { new { Name="Rex", Age=3 } };
  91. var sorted = pets.OrderBy(pet => pet.Name).ThenBy(pet =>
  92.  
  93. pet.Age);
  94. ====================================================
  95. Output dictionary by order of the values
  96. ---------
  97. foreach (KeyValuePair<string, int> item in
  98.  
  99. dictionary.OrderByDescending(key => key.Value))
  100. {
  101.    Console.WriteLine("{0} - {1}", item.Key, item.Value);
  102. }
  103. ====================================================
  104. using LINQ sorting and ordering arrays
  105. ---------
  106. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  107. var result = numbers.Where(num => num < 4 && num % 2 == 0).
  108.  
  109. OrderBy(num => num).Select(num => num * 2);
  110. ====================================================
  111. put in a list all posible pairs
  112. ----------
  113. string[] towns = { "Sofia", "Varna", "Pleven", "Ruse" };
  114. var pairs = (from firstTown in towns
  115.     from secondTown in towns
  116.     select new { First = firstTown, Second =
  117.  
  118. secondTown}).ToList();
  119. foreach (var townPair in pairs) {
  120.     Console.WriteLine("{0} : {1}", townPair.First,
  121.  
  122. townPair.Second);
  123.     }
  124. ====================================================
  125. LINQ:
  126. Operations
  127. -----------
  128. Where() - Searches by given condition
  129. First() / FirstOrDefault() - Gets the first element
  130. Last() / LastOrDefault() - Gets the last element
  131. Select() / Cast() - Makes projection (conversion) to other
  132.  
  133. type
  134. OrderBy() / ThenBy() / OrderByDescending() - Orders a
  135.  
  136. collection
  137. Any() - Checks if any element matches a condition
  138. All() - Checks if all elements match a condition
  139. ToArray()/ToList()/AsEnumerable() - Converts the collection
  140. Reverse() - Reverses a collection
  141.  
  142. Aggregation Methods
  143. -----------
  144. Average() - Calculates the average value of a collection
  145. Count() - Counts the elements in a collection
  146. Max() - Determines the maximum value of a collection
  147. Sum() - Sums the value in a collecition
  148. =====================================================
  149. How can I detect if this dictionary key exists?
  150. -----------
  151. if (dict.ContainsKey(key)) { ... }
  152. =====================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement