When I saw the Linq in action today, I suddenly had an idea. Use expression and Linq to quickly access the properties of an object. If we put an object in an array and query it, and then use Select to project the desired attributes, we can achieve the goal of fast access. It's a lot slower than direct access, but it's pretty good to be 1 orders of magnitude faster than reflection.
Suppose that there are entity classes defined as follows:
public class User
...{
public string Name
...{ get; set; }
public int Age
...{ get; set; }
}
This is necessary if we want to access the value of the Name field
var books = new User[] ...{ new User ...{Name = "Lucifer", Age = 26 } };
var val = books.Select(book => book.Name).First();It's very simple, then just translate it with expression and make it generic. The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions ;
using System.Diagnostics;
public class Quickaccess<t>
{
Static dictionary<int, delegate> __pmap = new Dictionary<int, delegate> ();
Static t[] __lst = new t[] ... {Default (T)};
public static P get_properyval<p> (T obj, string pname)
... {
var func = default (Func<t, p>);
__lst[0] = obj;
Try
... {
Func = (func<t, p>) __pmap[pname.gethashcode ()];
}
Catch
... {
/**//*
* from param in __lst
* Select Param.pname
* */
Var param = Expression.parameter (typeof (T), "Param");
var body = expression.property (param, pname);
var lambda = expression.lambda (body, param);
__pmap.add (Pname.gethashcode (), Lambda.compile ());
Func = (func<t, p>) __pmap[pname.gethashcode ()];
}
Return Enumerable.select (__lst, func). A ();
}
}
//calling code
int val = 0;
var user = new user ... {Name = ' lucifer ', age = 26};
Stopwatch SW1 = new stopwatch ();
SW1. Start ();
for (int i = 0; i < 10000000 ++i)
... {
val = quickaccess<user>. get_properyval<int> (User, "age");
}
SW1. Stop ();
Console.WriteLine (SW1. elapsedmilliseconds);
Although this code is not very practical but can reflect the power of LINQ and expression, thank you for watching.