Friday, 6 September 2013

Use LINQ expression to Update Property of object

Use LINQ expression to Update Property of object

So I have a situation where I need to dynamically update properties of my
object based on values contained. In the case below, I need to update the
value with replacing the first two characters of the current value with a
different string if condition is true.
PersonDetail.EvaluateConditionalRule("ID",
"((ID.Length > Convert.ToInt32(@0) ) AND
ID.Substring(Convert.ToInt32(@1), Convert.ToInt32(@2))
== @3 )",
new[] { "1", "0", "2", "SS" }, " ID = (@0 +
ID.Substring(Convert.ToInt32(@1))) " , new[] { "98",
"2" });
public static void EvaluateConditionalRule(this PersonDetail Detail,
String PropertyToEvaluate,
String ConditionalExpression, String[] parameters, String
IfTrueExpression,String[] IfTrueExpreassionparameters )
{
var property = Detail.GetType().GetProperties().Where(x =>
x.Name == PropertyToEvaluate).FirstOrDefault();
if (property == null)
throw new InvalidDataException(String.Format("Please
specify a valid {0} property name for the
evaluation.", Detail.GetType()));
//put together the condition like so
if (new[] { Detail
}.AsQueryable().Where(ConditionalExpression,
parameters).Count() > 0 && IfTrueExpression != null)
{
var result = new[] { Detail
}.AsQueryable().Select(IfTrueExpression,
IfTrueExpreassionparameters);
//Stuck Here as result does not contain expected value
property.SetValue( Detail,result , null);
}
}
Essentially what I want is, to be able to execute expressions fed this,
and I don't think I have the format right for the substring replace
expression to correctly evaluate. What I want from the above is something
like
ID = "98"+ ID.Substring(2);
Any help will be appreciated. Thanks

No comments:

Post a Comment