Lamdba小技巧

一般,我们是这么查找的:

        List lstStu = new List();
        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 lstStu = new List();
        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> a = Expression.Lambda>(
                Expression.Equal(memberExpression, constantExpression),
                parameterExpression);
        var k = lstStu.Where(a.Compile()).First();
        Console.WriteLine(k.Name);
        Console.ReadKey();

如此,只要传入要比较的类型名和对应值,就可以返回表达式了。
这个在制作entityframework仓储时,有一定作用:

public class SomeThing
{
    public Expression> test(string typeName,keyType kt)
    {
        ParameterExpression parameterExpression = Expression.Parameter(typeof(T));
        MemberExpression memberExpression = Expression.Property(parameterExpression, typeName);
        ConstantExpression constantExpression = Expression.Constant(kt);
        Expression> a = Expression.Lambda>(
                Expression.Equal(memberExpression, constantExpression),
                parameterExpression);

        return a;
    }

    public Expression> test2(string typeName, object kt)
    {
        var parameter = Expression.Parameter(typeof(T));

        Expression> a = Expression.Lambda>(
                   Expression.Equal(Expression.Property(parameter, typeName), Expression.Constant(kt)),
                   parameter);
        return a;
    }
    
}

你可能感兴趣的:(Lamdba小技巧)