views:

231

answers:

2

Hi,

I have a List of objects (string filename, BitmapImage image) to use as a cache of images.

private static readonly List<ImageData> imageCache = new List<ImageData>();

I created a Lookup to check this cache for an image each time it is required. If the image is not in the list it is added to the list.

The Looked is statically created

private static Lookup<string, ImageData> FileNameLookup = (Lookup<string, ImageData>)
               imageCache.ToLookup(data => data.ImageFileName, data => data);

However, unless I recreate the FileNameLookup each time I add an element to the list the Lookup never returns objects that do have the same file name.

public static void Reinit()
{
    FileNameLookup = (Lookup<string, ImageData>) imageCache.ToLookup(data =>
                                                 data.ImageFileName, data => data);
}

Should a Lookup only be used if the contents of the list is static? I can easily use a Dictionary but wanted to try a Lookup.

Cheers,

James

A: 

The FileNameLookup static variable is built from the contents of the imageCache list at some moment in time. If later you add a new element to the list this will not reflect the lookup. A dictionary would indeed be a better solution for caching if you cannot use the built-in ASP.NET cache.

Darin Dimitrov
A: 

Either use a Dictionary where filename is the key and image is the value

Or if you prefer to keep the ImageData object you can create a subclass of KeyedCollection that extracts the filename property and uses it as key:

class ImageCache : System.Collections.ObjectModel.KeyedCollection<string, ImageData>
{
    protected override string GetKeyForItem(ImageData item)
    {
        return item.ImageFileName;
    }
}

and use It like this

ImageCache c = new ImageCache();
string path = @"c:\somepath\image.jpg";
if (c.Contains(path))
{
    return c[path];
}
else
{
    // put something into the cache
}
jesperll