score:3
Accepted answer
You need to use an ExpressionVisitor to test the property values. Here is an example of how you could implement the logic.
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
// HasDivideByZero - the result should be -1
int result1 = Calcul<DataInfo>(new DataInfo { A = 10, B = 0, C = 1 }, x => x.A / x.B + x.C);
// HasNegative - the result should be 0
int result2 = Calcul<DataInfo>(new DataInfo { A = 10, B = 5, C = -1 }, x => x.A / x.B + x.C);
// the result should be 3
int result3 = Calcul<DataInfo>(new DataInfo { A = 10, B = 5, C = 1 }, x => x.A / x.B + x.C);
}
static int Calcul<T>(T data, Expression<Func<T, int>> query)
{
if (NegativeValueChecker<T>.HasNegative(data, query))
{
return 0;
}
if (DivideByZeroChecker<T>.HasDivideByZero(data, query))
{
return -1;
}
return query.Compile().Invoke(data);
}
}
class DivideByZeroChecker<T> : ExpressionVisitor
{
private readonly T _data;
private bool _hasDivideByZero;
public static bool HasDivideByZero(T data, Expression expression)
{
var visitor = new DivideByZeroChecker<T>(data);
visitor.Visit(expression);
return visitor._hasDivideByZero;
}
public DivideByZeroChecker(T data)
{
this._data = data;
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (!this._hasDivideByZero && node.NodeType == ExpressionType.Divide)
{
var rightMemeberExpression = (MemberExpression)node.Right;
var propertyInfo = (PropertyInfo)rightMemeberExpression.Member;
var value = Convert.ToInt32(propertyInfo.GetValue(this._data, null));
this._hasDivideByZero = value == 0;
}
return base.VisitBinary(node);
}
}
class NegativeValueChecker<T> : ExpressionVisitor
{
private readonly T _data;
public bool _hasNegative;
public static bool HasNegative(T data, Expression expression)
{
var visitor = new NegativeValueChecker<T>(data);
visitor.Visit(expression);
return visitor._hasNegative;
}
public NegativeValueChecker(T data)
{
this._data = data;
}
protected override Expression VisitMember(MemberExpression node)
{
if (!this._hasNegative)
{
var propertyInfo = (PropertyInfo)node.Member;
var value = Convert.ToInt32(propertyInfo.GetValue(this._data, null));
this._hasNegative = value < 0;
}
return base.VisitMember(node);
}
}
class DataInfo
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
}
}
score:0
Get a look at the source of Moq - http://code.google.com/p/moq/.
Source: stackoverflow.com
Related Articles
- How to extract properties used in a Expression<Func<T, TResult>> query and test their value?
- c# Linq or code to extract groups from a single list of source data
- Pass list of object properties to be used to form a new object inside a LINQ query
- How can I let users specify which entity properties are used in a Linq-to-Objects GroupBy query expression at runtime?
- Iterate through properties and values of an object returned via a linq query on a domain model
- Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator
- Could not find an implementation of the query pattern for source type 'System.Data.Entity.DbSet'
- LINQ To SQL exception: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains operator
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- Extract sql query from LINQ expressions
- How can I set properties on all items from a linq query with values from another object that is also pulled from a query?
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- Linq error - "NotSupportedException: Unsupported overload used for query operator 'Select'"
- Dapper nested object query - not populating all properties
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
- Linq to entities - SQL Query - Where list contains object with 2 properties (or more)
- Expanding properties for an IQueryable query
- LINQ Source Code Available
- Linq Query to Group By Multiple Columns But Get Additional Properties
- LINQ - 'Could not translate expression' with previously used and proven query condition
- prevent unnecessary cross joins in count query of generated sql code
- How to Query from Asp.Net Profile Properties using LINQ
- .NET 4 Code Contracts: "requires unproven: source != null"
- ObjectContext has been disposed throwed by EnsureConnection() in consecutive queries (No navigation properties used and no using())
- EF Code First comparing null values generates strange query
- LINQ query to detect duplicate properties in a list of objects
- linq - how do you do a query for items in one query source that are not in another one?
- EF6 Query Criteria using object properties that aren't null
- How can I write the following code more elegantly using LINQ query syntax?
- C# : LINQ query to list all empty properties of a class
- A cycle in LINQ expression
- LINQ Include with Inner Join isn´t Working
- LINQ Equal Operator Error in Query
- EF Core one-to-many with IQueryable
- Linq query, nested child objects in where, entity framework
- Handling null values in NHibernate LINQ
- Best way to call an instance method in Expression Trees?
- Return error message from a void method in C#
- “Grouping” dictionary by value of class property
- Rewrite foreach statement to linq
- Merge Lists within List that share same property C#
- Linq to sql table dynamically with ExecuteQuery VB
- Performing a time calculation inside a Linq query
- Grouping duplicate values in LINQ
- Is there any real difference between "and" and "wheres" in linq
- Rewriting this SQL in Lambda - using count and group by
- Check in an array of object
- Using LINQ for List of type object
- Infecting\transmitting value to the adjacent items of list, in C#
- Hide GridView Column using linq