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 Query
- How to extract properties used in a Expression<Func<T, TResult>> query and test their value?
- How to get the value of class properties with Linq query and IEnumerable
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- linq lamba how can i query a list of child properties and return the parent
- How to query and extract data from CSV file directly by LINQ
- How to extract common properties of a flat list of objects and build a nested list of the rest of properties
- how to fetch data from database using linq query for relationship 1:N and N:N (between 3 entity) in asp.net mvc EF code first?
- How to assign LINQ Query to a variable and then use it later in the code
- How can I let users specify which entity properties are used in a Linq-to-Objects GroupBy query expression at runtime?
- LINQ query on dotnet code and how concat will work here
- What does this C# code with an "arrow" mean and how is it called?
- Iterate through properties and values of an object returned via a linq query on a domain model
- How to Select Min and Max date values in Linq Query
- How to count the number of code lines in a C# solution, without comments and empty lines, and other redundant stuff, etc?
- 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
- How do I extract info deep inside XML using C# and LINQ?
- How to intercept and modify SQL query in Linq to SQL
- How to query if array is null or empty using MongoDB and C# Driver?
- LINQ - 'Could not translate expression' with previously used and proven query condition
- How do you query an object set and in that same query filter an attached entity collection?
- How to Query from Asp.Net Profile Properties using LINQ
- ObjectContext has been disposed throwed by EnsureConnection() in consecutive queries (No navigation properties used and no using())
- How to use Include and Anonymous Type in same query in Entity Framework?
- linq - how do you do a query for items in one query source that are not in another one?
- How can I write the following code more elegantly using LINQ query syntax?
- How to get "remainder" of query (all non-matched pairs) in LINQ and collect it in a list
- How can I code an outer join using LINQ and EF6?
- How to dynamic add filters to a LINQ query against an Odata Source in C#
- Avoid extra loop and could not find implementation of query pattern for source type int Select not found
More Query from same tag
- How to detect no data returned in C# LINQ query
- How can I use Left join in linq that we use in sql?
- LINQ: How to do JOIN using the linq extension method style on multiple fields?
- Dynamic Linq OR with int and string
- How to check multiple attributes having unique combination within List where attribute names are available as separate collection. [C#]
- Removing an item from a list - C#
- How to Select new model list after GroupBy mothod in Linq?
- Can Linq-To-Sql be aware of similarities of two tables?
- if only one record is return linq output is wrong c#
- Linq to objects List in list
- Only parameterless constructors and initializers are supported in LINQ to Entities error
- Query always returns previous value?
- LINQ2SQL Any(), NOT EXISTS Problems
- Query speed in SQL Server Management Studio (2008) vs NHibernate session.Query
- Northwind database JOIN QUERY between three tables (many to many)
- How to create an instance of a Nullable<T>?
- Converting a list of dynamic obects to a Dictionary<propertyName, Values>
- Dynamic JOIN - ON in LINQ Vb.net
- Linq to Entities with Linq to XML running very slowly
- group a table list by a column name (sample included)
- Does LINQ natively support splitting a collection in two?
- How to add multi let operator and orderby in linq
- LINQ to Entities does not recognize the method group join
- Filter out oldest item when items have the same name
- Linq Selector with dynamic property name
- Converting an entity model to a dataset - can this be done?
- An error occurred during the pre-login handshake
- How to Convert a LINQ Query Syntax to a Method Syntax? (with join and multiple selects) Issue: Where-no overloads for + 3 parameters
- LINQ Include slowing down performance when searching
- How to generate a LINQ query that queries all non-null properties from a search page model