Advertisement
Guest User

C# Answere

a guest
Jan 20th, 2015
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace SortAndSearch
  7. {
  8. class Person
  9. {
  10. public String name;
  11. public int personnummer;
  12.  
  13.  
  14. //Min metodkonstruktion
  15. public Person(string name, int personnummer)
  16. {
  17. this.name = name;
  18. this.personnummer = personnummer;
  19. }
  20. //Lägger till Get&set för båda
  21. public string getname()
  22. {
  23. return name;
  24.  
  25. }
  26. public void setname(string namn)
  27. {
  28. name = namn;
  29. }
  30. public int getPersonnummer()
  31. {
  32. return personnummer;
  33. }
  34. public void setPersonnummer(int nr)
  35. {
  36. personnummer = nr;
  37. }
  38.  
  39.  
  40. }
  41.  
  42. class program
  43. {
  44. static int LinearSearch(List<Person> list, int key)
  45. {
  46. for (int i = 0; i < list.Count; i++)
  47. {
  48. if (list[i].personnummer == key)
  49. return i;
  50.  
  51. }
  52. return -1;
  53.  
  54. }
  55.  
  56. static void Main(string[] args)
  57. {
  58. //Skapar en list av typen person
  59. List<Person> myList = new List<Person>();
  60.  
  61. myList.Add(new Person("Pontus Eriksson", 960219));
  62. myList.Add(new Person("Oliver Nilsson", 960228));
  63.  
  64. Console.WriteLine("Ange Personnumret du vill söka på: ");
  65. string str = Console.ReadLine();
  66. int key = Convert.ToInt32(str);
  67.  
  68. int index = LinearSearch(myList, key);
  69.  
  70. if (index == -1)
  71. Console.WriteLine("Personen finns ej med på listan");
  72. else
  73. Console.WriteLine("Personen med Personnummret: " + key + "Finns på Index: " + index + " och heter " + myList[index].name);
  74. Console.ReadKey();
  75. }
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement