Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for duplicates in arraylist

Tags:

c#

.net

asp.net

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

like image 998
anonym0use Avatar asked Nov 14 '08 11:11

anonym0use


People also ask

How do you check if an ArrayList contains duplicates?

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.

Does ArrayList contain duplicates?

ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.

How do you find duplicates in a List in Java?

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.


1 Answers

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>)

like image 60
Marc Gravell Avatar answered Oct 19 '22 02:10

Marc Gravell