Masoud
Masoud

Reputation: 1405

Add a specific number to a hashed object in C#

In a program I need to evaluate lots of objects. The result of evaluation is a double. for example

Object myObject = new Object(x,y,z);
double a = eval(myObject);

after this lots of other objects should be evaluated. I want to avoid reevaluating same objects. So I need to add evaluated objects and the evaluation result to a hash structure.

for example something like this after first evaluation: -------> this is a pseudo code

myHash.add(myObject, a);

Object anotherObject = new Object(x,y,z);

if (myHash.find(anotherObject))
   double evaluationForAnotherObject = myHash.get(anotherObject);

any help would be highly welcomed

Upvotes: 0

Views: 68

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108810

A Dictionary<TKey,TValue> can be used for such lookups:

Dictionary<object,double> dict=new Dictionary<object,double>();
if(dict.ContainsKey(obj))
  x=dict[obj];

It's important to use the correct equality comparer. For example on objects it uses referential equality by default. If your TKey type doesn't use the desired equality comparison you can supply an IEqualityComparer<TKey> to the constructor of the dictionary.

As an alternative you can pass your function into a memoizer. It returns a new function which caches the result of earlier computations. AFAIK the MiscUtil library contains one.

Func<object,double> memoizingEval=Memoizer.Memoize(eval);

and then use memoizingEval(obj)

Upvotes: 2

Related Questions