mardi 13 novembre 2018

How to dynamically create an Expression

I have a class like this:

    public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LOANIDBPM { get; set; }
    public string REPORTTYPE { get; set; }
}

I have a list Students, I want to filter some student in list by LOANIDBPM and REPORTTYPE.

Usually, this is the code (using linq)

        public void GetListStudent(List<Student> listStudent)
    {
        listStudent = listStudent.Where(x => x.LOANIDBPM == "MIKEN" && x.REPORTTYPE == "DX");
    }

However, for some reason, i can't Explicit "List", My solution is below:

        public void GetListStudent(object[] listStudent)
    {
        ParameterExpression param = Expression.Parameter(listStudent.First().GetType(), nameof(listStudent));
        Expression propLoanBPM = Expression.Property(param, "LOANIDBPM");
        Expression<Func<string>> loanIdLampda = () => "MIKEN";
        Expression searchLoanBPM = Expression.Equal(propLoanBPM, loanIdLampda.Body);

        Expression propReportType = Expression.Property(param, "REPORTTYPE");
        Expression<Func<string>> reportTypeLampda = () => "DX";

        Expression searchReportType = Expression.Equal(propReportType, reportTypeLampda.Body);

        Expression searchFinal = Expression.And(searchLoanBPM, searchReportType);


        Expression<Func<???, bool>> lampda = Expression.Lambda<Func<???, bool>>(searchFinal, param);

        listStudent = listStudent.Where(lampda).ToArray();
    }

The code above have two problems:

1: I don't know type of Student in Expression>, I can't use like:

Expression<Func< listStudent.First().GetType(), bool>> lampda = Expression.Lambda<Func< listStudent.First().GetType(), bool>>(searchFinal, param);

2: In Where method, it's need to IQueryable, but in my code is Expression>.

Sorry by my English. Thanks you so much





Aucun commentaire:

Enregistrer un commentaire