I’m trying to maintain a collection of objects based on their URI:
public class ConceptCollection : KeyedCollection<Uri, Concept> {
protected override Uri GetKeyForItem(Concept item) {
return item.Uri;
}
}
However, the URI regularly only differs based on the Fragment of the Uri. So, the following causes an error:
ConceptCollection wines = new ConceptCollection();
Concept red = new Concept("http://www.w3.org/2002/07/owl#RedWine");
Concept white = new Concept("http://www.w3.org/2002/07/owl#WhiteWine");
wines.Add(red);
wines.Add(white); // Error: An item with the same key has already been added.
Per http://msdn.microsoft.com/en-us/library/f83xtf15.aspx:
The Equals method compares the two
instances without regard to user
information ( UserInfo) and fragment (
Fragment) parts that they might
contain. For example, given the URIs
http://www.contoso.com/index.htm#search
and
http://user:password@www.contoso.com/index.htm,
the Equals method would return true.
I’m resigned to having to hack around this. But why does it behave this way? I can see the logic for user-info, but not for fragment.
From RFC 2396:
The emphasis added is mine and is the reason the fragment is not considered in the Uri.Equals implementation.
In your example, the URI for the resource you are retrieving is: http://www.w3.org/2002/07/owl
The fragments are processed by the user agent and have no meaning to or influence on the actual retrieval of the resource.