code_junkie

check for duplicates in arraylist

Nov 12th, 2011
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. List<Room> rooms = ...
  2. string roomType = "lounge";
  3. bool exists = rooms.Exists(delegate(Room room) { return room.Type == roomType; });
  4.  
  5. bool exists = rooms.Exists(room => room.Type == roomType);
  6.  
  7. bool exists = rooms.Any(room => room.Type == roomType);
  8.  
  9. if (!rooms.Any (r => r.RoomType == typeToFind /*kitchen, ...*/))
  10. //add it or whatever
  11.  
  12. if(rooms.ContainsKey(room.GetType()))
  13. {
  14. // Can't add a second room of the same type
  15. ...
  16. }
  17. else
  18. {
  19. rooms.Add(room.GetType(), room);
  20. }
  21.  
  22. void AddRoom(Room r, IList<Room> rooms, IDictionary<string, bool> roomTypes)
  23. {
  24. if (!roomTypes.Contains(r.RoomType))
  25. {
  26. rooms.Add(r);
  27. roomTypes.Add(r.RoomType, true);
  28. }
  29. }
  30.  
  31. Dictionary<Type, List<Room>> rooms = new Dictionary<Type, List<Room>>;
  32.  
  33. void Main(){
  34. KitchenRoom kr = new KitchenRoom();
  35. DummyRoom dr = new DummyRoom();
  36. RoomType1 rt1 = new RoomType1();
  37. ...
  38.  
  39. AddRoom(kr);
  40. AddRoom(dr);
  41. AddRoom(rt1);
  42. ...
  43.  
  44. }
  45.  
  46. void AddRoom(Room r){
  47. Type roomtype = r.GetType();
  48. if(!rooms.ContainsKey(roomtype){ //If the type is new, then add it with an empty list
  49. rooms.Add(roomtype, new List<Room>);
  50. }
  51. //And of course add the room.
  52. rooms[roomtype].Add(r);
  53. }
Add Comment
Please, Sign In to add comment