tags:

views:

1035

answers:

7

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)

Cheers

+1  A: 
if (!rooms.Any (r => r.RoomType == typeToFind /*kitchen, ...*/))
  //add it or whatever
Calamitous
ah my apologies am running on .net 2 unfortunately
anonym0use
With VS2008, this will work fine with .NET 2.
OJ
@OJ: with 2.0, only if you use LINQBridge... Any is provided by .NET 3.5; you could use the Exists syntax with C# 3.0 lambdas, however
Marc Gravell
Ah, the "Any" method ducked under my radar ;) But you don't need to use Any, you could use Find, which doesn't require LINQ.
OJ
+9  A: 

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

Marc Gravell
A: 

I havent got access to the linq technology as am running on .net 2.0. I should have stated that in the question. Apologies

anonym0use
LINQ? I don't see any LINQ. I see lambda expressions and anonymous delegates, but no LINQ. If you have VS 2008, you can still use these languages features in a .NET 2 application. They're just syntactic sugar.
OJ
@OJ: "Any" is a LINQ extension method, provided by Enumerable.Any in System.Core.dll, v3.5
Marc Gravell
A: 
Wolf5
A: 

Without using lambda expressions:

void AddRoom(Room r, IList<Room> rooms, IDictionary<string, bool> roomTypes)
{
   if (!roomTypes.Contains(r.RoomType))
   {
      rooms.Add(r);
      roomTypes.Add(r.RoomType, true);
   }
}

It doesn't actually matter what the type of the value in the dictionary is, because the only thing you're ever looking at is the keys.

Robert Rossney
A: 

Another way is to sort the array, then walk the elements until you find a pair of adjacent duplicates. Make it to the end, and the array is dupe-free.

David Grant
+1  A: 

From your question it's not 100% clear to me if you want to enforce the rule that there may be only one room of a given type, or if you simply want to know.

If you have the invariant that no collection of Rooms may have more than one of the same Room type, you might try using a Dictionary<Type, Room>.

This has the benefit of not performing a linear search on add.

You would add a room using the following operations:

if(rooms.ContainsKey(room.GetType()))
{
   // Can't add a second room of the same type
   ...
}
else
{
   rooms.Add(room.GetType(), room);
}
Kennet Belenky