C# 練習題 (14)

C# 練習題 (14)

練習題 (14):Adding/removing items in the beginning, middle and end of the array.

這一題我使用泛型 List 類別來實作,利用 Add、Insert 方法來將原宿放置在各位置;利用 RemoveAt 方法來移除特定位置的元素。

程式碼:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace ListTest
  4. {
  5. internal class Program
  6. {
  7. public static void printAll(List<int> l)
  8. {
  9. foreach ( int i in l)
  10. {
  11. Console.Write ( "{0} ", i);
  12. }
  13. Console.WriteLine ( );
  14. }
  15. private static void Main( string [ ] args)
  16. {
  17. List<int> l = new List<int>( );
  18. l.Add ( 1 );
  19. l.Add ( 2 );
  20. l.Add ( 3 );
  21. l.Add ( 5 );
  22. l.Add ( 6 );
  23. l.Add ( 7 );
  24. l.Add ( 8 );
  25. printAll(l);
  26. // Add items in the beginning
  27. l.Insert ( 0, 0 );
  28. printAll(l);
  29. // Add items in the middle
  30. l.Insert ( 4, 4 );
  31. printAll(l);
  32. // Add items in the end
  33. l.Add ( 9 );
  34. printAll(l);
  35. // remove items in the beginning
  36. l.RemoveAt ( 0 );
  37. printAll(l);
  38. // remove items in the middle
  39. l.RemoveAt ( 3 );
  40. printAll(l);
  41. // remove items in the end
  42. l.RemoveAt (l.Count - 1 );
  43. printAll(l);
  44. printAll(l);
  45. }
  46. }
  47. }