I have an arraylist that contains items called Room. Each Room has a roomtype such as kitchen, reception etc. I want to check the arraylist to see if any rooms of that type exist before adding it to the list. Can anyone recommend a neat way of doing this without the need for multiple foreach loops?
(.NET 2.0)
I havent got access to the linq technology as am running on .net 2.0. I should have stated that in the question. Apologies
One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.
I would not use ArrayList
here; since you have .NET 2.0, use List<T>
and all becomes simple:
List<Room> rooms = ...
string roomType = "lounge";
bool exists = rooms.Exists(delegate(Room room) { return room.Type == roomType; });
Or with C# 3.0 (still targetting .NET 2.0)
bool exists = rooms.Exists(room => room.Type == roomType);
Or with C# 3.0 and either LINQBridge or .NET 3.5:
bool exists = rooms.Any(room => room.Type == roomType);
(the Any
usage will work with more types, not just List<T>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With