一般,我们是这么查找的:
List<Student> lstStu = new List<Student>();
for (int i = 1; i < 10; i++)
{
Student stu = new Student();
stu.ID = i;
stu.Name = "k" + i;
stu.stuNo = Guid.NewGuid();
lstStu.Add(stu);
}
Student s = lstStu.Where(w => w.ID == 1).First();
如果不想在where里面写表达式,或者有时候查的未必是ID,想做个通用方法:
List<Student> lstStu = new List<Student>();
for (int i = 1; i < 10; i++)
{
Student stu = new Student();
stu.ID = i;
stu.Name = "k"+i;
stu.stuNo = Guid.NewGuid();
lstStu.Add(stu);
}
int id = 3;//属性名对应的值,类型必须与属性的类型相同
string typeName = "ID";//要查找的属性名
ParameterExpression parameterExpression = Expression.Parameter(typeof(Student));
MemberExpression memberExpression = Expression.Property(parameterExpression, typeName);
ConstantExpression constantExpression = Expression.Constant(id);
Expression<Func<Student, bool>> a = Expression.Lambda<Func<Student, bool>>(
Expression.Equal(memberExpression, constantExpression),
parameterExpression);
var k = lstStu.Where(a.Compile()).First();
Console.WriteLine(k.Name);
Console.ReadKey();
如此,只要传入要比较的类型名和对应值,就可以返回表达式了。
这个在制作entityframework仓储时,有一定作用:
public class SomeThing<T,keyType>
{
public Expression<Func<T, bool>> test(string typeName,keyType kt)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(T));
MemberExpression memberExpression = Expression.Property(parameterExpression, typeName);
ConstantExpression constantExpression = Expression.Constant(kt);
Expression<Func<T, bool>> a = Expression.Lambda<Func<T, bool>>(
Expression.Equal(memberExpression, constantExpression),
parameterExpression);
return a;
}
public Expression<Func<T, bool>> test2(string typeName, object kt)
{
var parameter = Expression.Parameter(typeof(T));
Expression<Func<T, bool>> a = Expression.Lambda<Func<T, bool>>(
Expression.Equal(Expression.Property(parameter, typeName), Expression.Constant(kt)),
parameter);
return a;
}
}
网友评论