美文网首页
Lamdba小技巧

Lamdba小技巧

作者: 小狼在IT | 来源:发表于2018-05-23 12:30 被阅读0次

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

        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;
    }
    
}

相关文章

网友评论

      本文标题:Lamdba小技巧

      本文链接:https://www.haomeiwen.com/subject/nicrjftx.html