Get the parameters in an expression using NCalc - c#

I have an expression which I want to parse to get a list of all used parameters.
For example: "X + 5 / (Y - 1)" should give me the following result: X,
Y
I already use NCalc in my project; so is it possible to use NCalc to get the parameters used in an expression?
According to this one discussion entry (https://ncalc.codeplex.com/discussions/361959) it is, but I don't quite understand the answer.

From the discussion/answer here: http://ncalc.codeplex.com/discussions/360990
A implementation that I've tested and works (for your provided sample expression) is to implement a LogicalExpressionVisitor and have it record the parameters as they are found:
class ParameterExtractionVisitor : LogicalExpressionVisitor
{
public HashSet<string> Parameters = new HashSet<string>();
public override void Visit(NCalc.Domain.Identifier function)
{
//Parameter - add to list
Parameters.Add(function.Name);
}
public override void Visit(NCalc.Domain.UnaryExpression expression)
{
expression.Expression.Accept(this);
}
public override void Visit(NCalc.Domain.BinaryExpression expression)
{
//Visit left and right
expression.LeftExpression.Accept(this);
expression.RightExpression.Accept(this);
}
public override void Visit(NCalc.Domain.TernaryExpression expression)
{
//Visit left, right and middle
expression.LeftExpression.Accept(this);
expression.RightExpression.Accept(this);
expression.MiddleExpression.Accept(this);
}
public override void Visit(Function function)
{
foreach (var expression in function.Expressions)
{
expression.Accept(this);
}
}
public override void Visit(LogicalExpression expression)
{
}
public override void Visit(ValueExpression expression)
{
}
}
Then you would use it as:
var expression = NCalc.Expression.Compile("2 * [x] ^ 2 + 5 * [y]", false);
ParameterExtractionVisitor visitor = new ParameterExtractionVisitor();
expression.Accept(visitor);
var extractedParameters = visitor.Parameters;
foreach (var param in extractedParameters)
Console.WriteLine(param);
This outputs "x" and "y" for me.
Note the use of HashSet in the ParameterExtractionVisitor. This is because if your expression contains the same variable more than once (for example: "[x] + [x]") it will be added twice. If you want to store an entry each time the same variable is used, replace the HashSet with a List.
That all said, I have very little experience with NCalc, so my implementation of the overridden methods of LogicalExpressionVisitor are guesses. When I overrode the void Visit(ValueExpression expression) method with expression.Accept(this), it resulted in a StackOverflowException. So I simply left the implementation blank and it seemed to work. So I would suggest that you take my answer here with a very large grain of salt. Your mileage may vary and I can't say if this works for all types of expressions.

This works for me. Your mileage may vary.
public List<string> GetParameters(string expression) {
List<string> parameters = new List<string>();
Random random = new Random();
NCalc.Expression e = new NCalc.Expression(expression);
e.EvaluateFunction += delegate(string name, NCalc.FunctionArgs args) {
args.EvaluateParameters();
args.Result = random.Next(0, 100);
};
e.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args) {
parameters.Add(name);
args.Result = random.Next(0, 100);
};
try {
e.Evaluate();
}
catch {
}
return parameters;
}
ref: https://ncalc.codeplex.com/discussions/79258#editor

Here is another approach I use:
I built a NCalc extension method that allows to process parameters and functions on the fly.
internal static class NCalcExtensions
{
public static object Evaluate(this Expression exp, EvaluateParameterHandler evaluateParameters = null, EvaluateFunctionHandler evaluateFunctions = null)
{
try
{
if (evaluateParameters != null)
exp.EvaluateParameter += evaluateParameters;
if (evaluateFunctions != null)
exp.EvaluateFunction += evaluateFunctions;
return exp.Evaluate();
}
finally
{
exp.EvaluateParameter -= evaluateParameters;
exp.EvaluateFunction -= evaluateFunctions;
}
}
}
Among other things, I can use it to run a dummy evaluation to get parameters and functions names.
var paramNames = new List<string>();
var functionNames = new List<string>();
expression.Evaluate(
new EvaluateParameterHandler((s, a) =>
{
paramNames.Add(s);
a.Result = 1; // dummy value
}),
new EvaluateFunctionHandler((s, a) =>
{
functionNames.Add(s);
a.Result = 1; // dummy value
}));

Based on Chris Sinclairs answer, now is very popular NCalcAsync nuget package. In that case, you can have something like this:
class ParameterExtractionVisitor : LogicalExpressionVisitor
{
public HashSet<string> Parameters = new();
public override Task VisitAsync(Identifier function)
{
//Parameter - add to list
Parameters.Add(function.Name);
return Task.CompletedTask;
}
public override async Task VisitAsync(UnaryExpression expression)
{
await expression.Expression.AcceptAsync(this);
}
public override async Task VisitAsync(BinaryExpression expression)
{
//Visit left and right
await expression.LeftExpression.AcceptAsync(this);
await expression.RightExpression.AcceptAsync(this);
}
public override async Task VisitAsync(TernaryExpression expression)
{
//Visit left, right and middle
await expression.LeftExpression.AcceptAsync(this);
await expression.RightExpression.AcceptAsync(this);
await expression.MiddleExpression.AcceptAsync(this);
}
public override async Task VisitAsync(Function function)
{
foreach (var expression in function.Expressions)
{
await expression.AcceptAsync(this);
}
}
public override Task VisitAsync(LogicalExpression expression)
{
return Task.CompletedTask;
}
public override Task VisitAsync(ValueExpression expression)
{
return Task.CompletedTask;
}
}

Related

Convert Expression<Action<T>> to Expression<Func<T>>

I have Expression<Action<T>> where Action is call of function, but function result is not used. Let's consider the following code sample:
using System;
using System.Linq.Expressions;
namespace ConsoleApp
{
class Program
{
public class MyArg
{
public int Data { get; set; }
}
public class MyExecutor
{
public bool Executed { get; set; }
public int MyMethod(int simpleArg, MyArg complexArg)
{
int result = simpleArg + complexArg.Data;
this.Executed = true;
return result;
}
}
static void Main(string[] args)
{
Expression<Action<MyExecutor>> expr = t => t.MyMethod(2, new MyArg { Data = 3 });
var executor = new MyExecutor();
Action<MyExecutor> action = expr.Compile();
action(executor);
Console.WriteLine(executor.Executed); // true
}
}
}
There can lot of different actions, with different number of arguments. In all cases I have only such kind of expr which always calls a function and that function always returns the same type, in my example above it is int.
I need to have something like this:
static Expression<Func<MyExecutor, int>> ToExpressionOfFunc(Expression<Action<MyExecutor>> expr)
{
// TODO
throw new NotImplementedException();
}
to be able to make a call like this:
Expression<Func<MyExecutor, int>> funcExpr = ToExpressionOfFunc(expr);
Func<MyExecutor, int> func = funcExpr.Compile();
int result = func(executor);
Console.WriteLine(result); // should print 5
I have a feeling that this should be possible but have no ideas where to start from. I see in debug that there is an expr.Body.Method with desired ReturnType of Int32, but not clear how to extract it properly to the new Expression<Func>.
It's simple, just create a new Expression<Func<MyExecutor, int>> using the body and parameters from the existing expression:
static Expression<Func<MyExecutor, int>> ToExpressionOfFunc(Expression<Action<MyExecutor>> expr)
{
return Expression.Lambda<Func<MyExecutor, int>>(expr.Body, expr.Parameters);
}
Note that this throws an exception if expr is not of return type int.

Get expression arguments?

Ok, here is the problem:
int a = 111;
int b = 222;
Expression<Func<int>> expr = ()=> someClass.SomeWork(a) + b + 1;
As you see, there is 3 different arguments: someClass, a, b. They are all from another scope of execution, but one isn't. How I can get them? I mean, in general, I want only variables of outter scope.
For example, I want to use it like this:
var result = InvokeAndLog(expr);//this will invoke expression and print out everything I need from these arguments.
Ok, folks, I found answer myself. And here it is:
internal class Program
{
public static int Method1()
{
return new Random(0).Next(10000);
}
public class MyClass
{
private int var = 11111;
public int GetSome(int val)
{
return var * val;
}
}
private static void Main()
{
var clas = new MyClass();
int a = 111;
int b = 222;
Expression<Func<int>> expr = () => a * 2 - clas.GetSome(b) + b + 1 - Method1();
var result = InvokeAndLog(expr);
}
private static T InvokeAndLog<T>(Expression<Func<T>> expr)
{
var visitor = new ArgumentsVisitor();
visitor.Visit(expr);
Console.WriteLine("Inputs: {0}", string.Join(", ", visitor.Arguments));
return expr.Compile()();
}
}
The main class here is ExpressionVisitor descendant. I just overrided its member visitor and aggregated all members into single set:
public class ArgumentsVisitor : ExpressionVisitor
{
private readonly HashSet<MemberInfo> _all = new HashSet<MemberInfo>();
public IEnumerable<MemberInfo> Arguments
{
get { return _all; }
}
protected override Expression VisitMember(MemberExpression node)
{
_all.Add(node.Member);
return base.VisitMember(node);
}
}
Then I applyed visitor to expression and printed out all variables! Thanks, microsoft =)

How to get arguments from an Expression where TDelegate is a callback

I'm attempting to write a simple generic cache but running into problems with generating unique enough keys with using System.Func as a callback.
What I ideally want is to be able to pass in an invocable delegate of some description so that the cache itself can get the value, and determine a key all from the same expression. Right now I'm getting exceptions because I'm not passing in an argument that implements or inherits from MethodCallExpression. What should I be using instead of a System.Func for this intended behaviour?
public class SimpleCacheKeyGenerator : ICacheKey
{
public string GetCacheKey<T>(Expression<Func<T>> action)
{
var body = (MethodCallExpression) action.Body; //!!! Exception Raised - action.Body is FieldExpression
ICollection<object> parameters = (from MemberExpression expression in body.Arguments
select
((FieldInfo) expression.Member).GetValue(
((ConstantExpression) expression.Expression).Value)).ToList();
var sb = new StringBuilder(100);
sb.Append(body.Type.Namespace);
sb.Append("-");
sb.Append(body.Method.Name);
parameters.ToList().ForEach(x =>
{
sb.Append("-");
sb.Append(x);
});
return sb.ToString();
}
}
public class InMemoryCache : ICacheService
{
private readonly ICachePolicy _cachePolicy;
private readonly ICacheKey _cacheKey;
public InMemoryCache(ICachePolicy cachePolicy, ICacheKey cacheKey)
{
_cachePolicy = cachePolicy;
_cacheKey = cacheKey;
}
public T Get<T>(Func<T> getItemCallback) where T : class
{
var cacheID = _cacheKey.GetCacheKey(() => getItemCallback);
var item = HttpRuntime.Cache.Get(cacheID) as T;
if (item == null)
{
item = getItemCallback();
if (_cachePolicy.RenewLeaseOnAccess)
{
HttpContext.Current.Cache.Insert(cacheID, getItemCallback, null, System.Web.Caching.Cache.NoAbsoluteExpiration, _cachePolicy.ExpiresAfter);
}
else
{
HttpContext.Current.Cache.Insert(cacheID, getItemCallback, null, DateTime.UtcNow + _cachePolicy.ExpiresAfter, System.Web.Caching.Cache.NoSlidingExpiration);
}
}
return item;
}
}
The problem is, you can't easily use both the Expression> and Func representing the same thing without duplicating the code.
You could possibly convert Expression> to a Func with LambdaExpression>.Compile() method, but that could create a performance problem, since Compile actually uses assembly emit, which is quite expensive.
Here is how i would implement the same thing without using Expressions and compilation.
You can find the same pattern everywhere in the standard Linq extensions.
Pass your argument as a separate object.
The type you use as an argument will be used for type inference for the delegate, and the argument itself will provide the arguments for the delegate at the same type.
Note that the cache in this implementation works because of the default ToString implementation of the anonimous objects used as arguments.
void Main()
{
var computeCount = 0;
var item1 = GetCached(new{x = 1, y = 2}, (arg)=>{computeCount++; return arg.x + arg.y;});
Console.WriteLine(item1);
var item2 = GetCached(new{x = 1, y = 2}, (arg)=>{computeCount++; return arg.x + arg.y;});
Console.WriteLine(item2);
var item3 = GetCached(new{x = 1, y = 3}, (arg)=>{computeCount++; return arg.x + arg.y;});
Console.WriteLine(item3);
Console.WriteLine("Compute count:");
Console.WriteLine(computeCount);
}
Dictionary<string, object> _cache = new Dictionary<string, object>();
E GetCached<T, E>(T arg, Func<T,E> getter)
{
// Creating the cache key.
// Assuming T implements ToString correctly for cache to work.
var cacheKey = arg.ToString();
object result;
if (!_cache.TryGetValue(cacheKey, out result))
{
var newItem = getter(arg);
_cache.Add(cacheKey, newItem);
return newItem;
}
else
{
Console.WriteLine("Cache hit: {0}", cacheKey);
}
return (E)result;
}
Console output:
3
Cache hit: { x = 1, y = 2 }
3
4
Compute count:
2
You get this exception because (() => getItemCallback) means (() => { return getItemCallback; })
That's why action.Body is not a method call, it is the return statement. If you change your code to (() => getItemCallback()) you should not have the error. But you won't have any arguments.
To obtain arguments of the base call, you will have to change your code to accept an Expression and Compile your lambda.
public T Get<T>(Expression<Func<T>> getItemCallbackExpression) where T : class
{
var cacheID = _cacheKey.GetCacheKey(getItemCallbackExpression);
var item = HttpRuntime.Cache.Get(cacheID) as T;
if (item == null)
{
item = getItemCallback.Compile()();
if (_cachePolicy.RenewLeaseOnAccess)
{
HttpContext.Current.Cache.Insert(cacheID, getItemCallback, null, System.Web.Caching.Cache.NoAbsoluteExpiration, _cachePolicy.ExpiresAfter);
}
else
{
HttpContext.Current.Cache.Insert(cacheID, getItemCallback, null, DateTime.UtcNow + _cachePolicy.ExpiresAfter, System.Web.Caching.Cache.NoSlidingExpiration);
}
}
return item;
}
I won't recommend this approach because compiling an expression takes time.
It may be easier and more performant to manually generate cache keys. If you really want to automatically manage cache keys. You may have a look to Aspect Oriented Programmation using castle.Core or PostSharp. Theses tools will allow you to automatically add code to some of your methods and automatically add cache logic.
I modified the code as below, I got the expected result this way, so you can try this, I hope this would be helpful.
public class SimpleCacheKeyGenerator
{
public string GetCacheKey<T, TObject>(Expression<Func<T, TObject>> action)
{
var body = (MethodCallExpression) action.Body;
ICollection<object> parameters = body.Arguments.Select(x => ((ConstantExpression) x).Value).ToList();
var sb = new StringBuilder(100);
sb.Append(body.Type.Namespace);
sb.Append("-");
sb.Append(body.Method.Name);
parameters.ToList().ForEach(x =>
{
sb.Append("-");
sb.Append(x);
});
return sb.ToString();
}
}
public class InMemoryCache
{
public void Get<T, TObject>(Expression<Func<T, TObject>> getItemCallback)
{
var generator = new SimpleCacheKeyGenerator();
Console.WriteLine(generator.GetCacheKey(getItemCallback));
}
}
main:
private static void Main(string[] args)
{
var cache = new InMemoryCache();
var tt = new SomeContextImpl();
cache.Get<SomeContextImpl, string>(x => x.Any("hello", "hi"));
Console.ReadKey();
}
somcontextimpl:
public class SomeContextImpl
{
public string Any(string parameter1, string parameter2) { return ""; }
}

When are parameters in a lambda expression prefered?

This is kind of a weird question but it came up the other day and it has me thinking.
When is it preferable design to use lambda expressions in this form ".(x => x.Whatever)" verse ".(() => obj.Whatever)".
Consider the following extension methods.
public static class ExtensionMethods
{
public static string TryToGetTheString<T>(this T value, Func<T, string> method)
{
try
{
return method(value);
}
catch (Exception)
{
return "banana";
}
}
public static string TryToGetTheStringTwo<T>(this T value, Func<string> method)
{
try
{
return method();
}
catch (Exception)
{
return "banana";
}
}
}
And the following self referencing class.
public class testClass5000
{
private int? _id;
public int? ID { get { return _id; } set { _id = value; } }
private string _urgh;
public string Urgh { get; set; }
public testClass5000 tc5k { get; set; }
}
Then using an extremely lazy process to avoid checking for nulls, while attempting to get a string (Urgh) from testClass5000, you could implement the extension methods and class like such,
private void main()
{
var tc = new testClass5000();
textBox1.text = tc.TryToGetTheString(x => x.tc5k.tc5k.tc5k.Urgh);
}
However, since tc is declared locally the following also works.
private void main()
{
var tc = new testClass5000();
textBox1.text = tc.TryToGetTheStringTwo(() => tc.tc5k.tc5k.tc5k.Urgh);
}
I am curious when (x => x.tc5k.tc5k.tc5k.Urgh) is necessary and when (() => tc.tc5k.tc5k.tc5k.Urgh) is preferable.
//////////////////////////////////////////
I did come up with the following scenario where passing the parameter seems preferable.
With the following extension methods.
public static class ExtensionMethods
{
public static T TestOne<T>(this T value, Func<T, T> method)
{
try
{
return method(value);
}
catch (Exception)
{
return default(T);
}
}
public static T TestTwo<T>(this T value, Func<T> method)
{
try
{
return method();
}
catch (Exception)
{
return default(T);
}
}
}
And using the following code.
private void Form1_Load(object sender, EventArgs e)
{
var firstValue = 5;
var secondValue = 10;
var resultOne = firstValue.TestOne(x => x + 1).TestOne(x => x * 2);
//returns 12
var resultTwo = secondValue.TestTwo(() => secondValue + 1).TestTwo(() => secondValue * 2);
//returns 20
var resultThree = secondValue.TestTwo(() => secondValue.TestTwo(() => secondValue + 1) * 2);
//returns 22
}
In this example .TestOne(x => x + 1).TestOne(x => x * 2) is preferable notation because to achieve the same thing without passing a paremeter you need to start nesting expressions.
Injecting the parameters values directly in the lambda is more costly, because the compiler has to create a special class just for this purpose.
If we exclude performance considerations, then I would say that injecting the parameter is easier to write (personal preference here), and keeping the parameters in the prototype ( (x,y) => // do something) is useful when you're not actually the one providing the value of the parameters. For instance, when using the Select Linq query. Or I often use that for load balancing scenarios (a lambda "service => service.SomeFunction()", then a special factory retrieve the service and execute the lambda).
In cases where the parameters are simply not the same as the original value you provided.
A crude example
public static class Extensions
{
public static void DoSomething(this string s,Action<string> action)
{
var something = Enumerable.Range(1,100).Select(i=> String.Format("{0}_{1}",s,i));
foreach (var ss in something)
{
action(ss);
}
}
}
Then
var something = "ABC123";
something.DoSomething(x=>Console.WriteLine(x));
//Ignoring that we could do something.DoSomething(Console.WriteLine);
Obviously without the parameter you cant access the actual value you are insterested in, and the original value is of no use within this concept.

Is it possible to cache a value evaluated in a lambda expression?

In the ContainsIngredients method in the following code, is it possible to cache the p.Ingredients value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside p eg. p.InnerObject.ExpensiveMethod().Value
edit:
I'm using the PredicateBuilder from http://www.albahari.com/nutshell/predicatebuilder.html
public class IngredientBag
{
private readonly Dictionary<string, string> _ingredients = new Dictionary<string, string>();
public void Add(string type, string name)
{
_ingredients.Add(type, name);
}
public string Get(string type)
{
return _ingredients[type];
}
public bool Contains(string type)
{
return _ingredients.ContainsKey(type);
}
}
public class Potion
{
public IngredientBag Ingredients { get; private set;}
public string Name {get; private set;}
public Potion(string name) : this(name, null)
{
}
public Potion(string name, IngredientBag ingredients)
{
Name = name;
Ingredients = ingredients;
}
public static Expression<Func<Potion, bool>>
ContainsIngredients(string ingredientType, params string[] ingredients)
{
var predicate = PredicateBuilder.False<Potion>();
// Here, I'm accessing p.Ingredients several times in one
// expression. Is there any way to cache this value and
// reference the cached value in the expression?
foreach (var ingredient in ingredients)
{
var temp = ingredient;
predicate = predicate.Or (
p => p.Ingredients != null &&
p.Ingredients.Contains(ingredientType) &&
p.Ingredients.Get(ingredientType).Contains(temp));
}
return predicate;
}
}
[STAThread]
static void Main()
{
var potions = new List<Potion>
{
new Potion("Invisibility", new IngredientBag()),
new Potion("Bonus"),
new Potion("Speed", new IngredientBag()),
new Potion("Strength", new IngredientBag()),
new Potion("Dummy Potion")
};
potions[0].Ingredients.Add("solid", "Eye of Newt");
potions[0].Ingredients.Add("liquid", "Gall of Peacock");
potions[0].Ingredients.Add("gas", "Breath of Spider");
potions[2].Ingredients.Add("solid", "Hair of Toad");
potions[2].Ingredients.Add("gas", "Peacock's anguish");
potions[3].Ingredients.Add("liquid", "Peacock Sweat");
potions[3].Ingredients.Add("gas", "Newt's aura");
var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad")
.Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion"));
foreach (var result in
from p in potions
where(predicate).Compile()(p)
select p)
{
Console.WriteLine(result.Name);
}
}
Have you considered Memoization?
The basic idea is this; if you have an expensive function call, there is a function which will calculate the expensive value on first call, but return a cached version thereafter. The function looks like this;
static Func<T> Remember<T>(Func<T> GetExpensiveValue)
{
bool isCached= false;
T cachedResult = default(T);
return () =>
{
if (!isCached)
{
cachedResult = GetExpensiveValue();
isCached = true;
}
return cachedResult;
};
}
This means you can write this;
// here's something that takes ages to calculate
Func<string> MyExpensiveMethod = () =>
{
System.Threading.Thread.Sleep(5000);
return "that took ages!";
};
// and heres a function call that only calculates it the once.
Func<string> CachedMethod = Remember(() => MyExpensiveMethod());
// only the first line takes five seconds;
// the second and third calls are instant.
Console.WriteLine(CachedMethod());
Console.WriteLine(CachedMethod());
Console.WriteLine(CachedMethod());
As a general strategy, it might help.
Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.Ingredients as a parameter...
private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)
{
return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient);
}
public static Expression<Func<Potion, bool>>
ContainsIngredients(string ingredientType, params string[] ingredients)
{
var predicate = PredicateBuilder.False<Potion>();
// Here, I'm accessing p.Ingredients several times in one
// expression. Is there any way to cache this value and
// reference the cached value in the expression?
foreach (var ingredient in ingredients)
{
var temp = ingredient;
predicate = predicate.Or(
p => IsIngredientPresent(p.Ingredients, ingredientType, temp));
}
return predicate;
}
Well, in this case, if you can't use Memoization, you're rather restricted since you can really only use the stack as your cache: You've got no way to declare a new variable at the scope you'll need. All I can think of (and I'm not claiming it will be pretty) that will do what you want but retain the composability you need would be something like...
private static bool TestWith<T>(T cached, Func<T, bool> predicate)
{
return predicate(cached);
}
public static Expression<Func<Potion, bool>>
ContainsIngredients(string ingredientType, params string[] ingredients)
{
var predicate = PredicateBuilder.False<Potion>();
// Here, I'm accessing p.Ingredients several times in one
// expression. Is there any way to cache this value and
// reference the cached value in the expression?
foreach (var ingredient in ingredients)
{
var temp = ingredient;
predicate = predicate.Or (
p => TestWith(p.Ingredients,
i => i != null &&
i.Contains(ingredientType) &&
i.Get(ingredientType).Contains(temp));
}
return predicate;
}
You could combine together the results from multiple TestWith calls into a more complex boolean expression where required - caching the appropriate expensive value with each call - or you can nest them within the lambdas passed as the second parameter to deal with your complex deep hierarchies.
It would be quite hard to read code though and since you might be introducing a bunch more stack transitions with all the TestWith calls, whether it improves performance would depend on just how expensive your ExpensiveCall() was.
As a note, there won't be any inlining in the original example as suggested by another answer since the expression compiler doesn't do that level of optimisation as far as I know.
I would say no in this case. I assume that the compiler can figure out that it uses the p.Ingredients variable 3 times and will keep the variable closeby on the stack or the registers or whatever it uses.
Turbulent Intellect has the exactly right answer.
I just want to advise that you can strip some of the nulls and exceptions out of the types you are using to make it friendlier to use them.
public class IngredientBag
{
private Dictionary<string, string> _ingredients =
new Dictionary<string, string>();
public void Add(string type, string name)
{
_ingredients[type] = name;
}
public string Get(string type)
{
return _ingredients.ContainsKey(type) ? _ingredients[type] : null;
}
public bool Has(string type, string name)
{
return name == null ? false : this.Get(type) == name;
}
}
public Potion(string name) : this(name, new IngredientBag()) { }
Then, if you have the query parameters in this structure...
Dictionary<string, List<string>> ingredients;
You can write the query like this.
from p in Potions
where ingredients.Any(i => i.Value.Any(v => p.IngredientBag.Has(i.Key, v))
select p;
PS, why readonly?

Categories

Resources