Problem

I have a bunch of Trade objects that internally store two players (involved in the trade). I was thinking of storing these Trade objects in a hashtable so I could index them with the key using the value of the two players respective names.

What do I want to do?

Get to the trade object by knowing the two people inside it.Rather than use a Hashtale I thought I might poke around with a LinkedList for fun. I didn’t want to have to iterate over the collection looking for the trade object with these players in it. So how could I get access to the right Trade object?I implemented the Comparable interface so I could define how Trade objects were compared.

#region IComparable Members
public int CompareTo(object obj)
{
if (obj is Trade) {
  Trade t2 = (Trade)obj;
  if (t2._Player1.Name.Equals(_Player1.Name,StringComparison.OrdinalIgnoreCase)
     && t2._Player2.Name.Equals(_Player2.Name,StringComparison.OrdinalIgnoreCase)
     || (t2._Player1.Name.Equals(_Player2.Name,StringComparison.OrdinalIgnoreCase)
     && t2._Player2.Name.Equals(_Player1.Name,StringComparison.OrdinalIgnoreCase)))
     return 0;
  else return -1;
}
return -1;
}
#endregion

I then overrode the Equals method to call this method I had defined.

public override bool Equals(object obj) {
return CompareTo(obj) == 0;
}

Assuming I knew the players but wanted the Trade object associated with these players I could do the following.

Trade tradeObject = null;
Player p1 = new Player("player1");
Player p2 = new Player("player2");
// A predicate pointing to the Equals method of my dummy
Trade objectPredicate compare = new Predicate(dummyTrade.Equals);
// Does a Trade object matching this Predicate// exist in the LinkedList?
if (_TradeList.Exists(compare))
tradeObject = _TradeList[_TradeList.IndexOf(dummyTrade)];

So what does a .NET Predicate give me?

Find a specific Trade object in the LinkedList who internally has a reference to the two specified players. An indirect way of finding the trade object you want when you only know the players associated with that Trade object.

Why whould you do this?

 You wouldn’t. A hashtable would be much faster O(1) (assuming no collision recovery need be performed) as you could assign the key a some combination of the players names.

Don’t all collections have a .Contains(object) method?

Yes but this does not use .Equals() for equality. It uses == to check if two objects are exactly the same. Remeber I used a dummy trade object to find the real trade object. This would not have been possible.I’m not sure how internally the Exists() and Find() methods work but they probably still have to iterate over the collection so using an Iterator in the first place would be simpler and easier.I haven’t played around with .NET predicates before so it was a bit of fun :)