views:

196

answers:

3

So I've been trying to figure out the most efficient way to pull off this trick:

I have a two column primary key in the database (an int and a string) and I'm trying to make a cache (I like using dictionaries) and I need to have a way to reference the two values as a key to get the object out.

The key is

private struct PageNameOnSite
{
    public int siteId;
    public string pageName;
}

It was suggested to me that I make a class to wrap this instead but that doesn't sound like the best way to use memory once this thing gets 10,000 entries put in it. My understanding that the memory footprint of a struct is smaller than that of a class.

+2  A: 

Why not use the PageNameOnSise the key to the Dictionary? You'd need to override a few things but it's not too bad.

private struct PageNameOnSite
{
    public int siteId;
    public string pageName;
    public override bool Equals(object obj) {
      if ( !obj is PageNameOnSite) { return false; }
      var other = (PageNameOnSite)obj;
      return sideId == other.siteId && StringComparer.Oridinal.Equals(pageName, other.pageName);
   }
   public override int GetHashCode() { return sideId + pageName.GetHashCode(); }
}

Then you can just use a quick lookup with an id pageName pair

public static object Loopup(Dictionary<PageNameOnSite,object> map, int id, string name) {
  var key = new PageNameOnSite() { siteId = id, pageName = name};
  return map[key];
}
JaredPar
A: 

If you do choose to go with the class option to which you alluded. This is quite possible and Code Project has posted a great article.

In short, you use a class as the key and define a custom comparer. As you said, classes can have a larger footprint than structs and this one will. The other question is, if you do need to use a super large collection of data locally, maybe there is a better method.

Instead of loading it into memory, perhaps you should use a "mobile" database, most full powered databases offer these stripped down, easily deployable alternatives. Good luck!

Michael La Voie
+1  A: 

Here's an answer that adheres to KISS:

Why not generate a string as your key, like site|page, i.e., for site = 1 and page=default.aspx, use 1|default.aspx?

I realize it's not the cool OOP way to go, but if your key changes, you'll be changing code anyway.

Moose