使用反射让linq实现动态查询, 类似拼接sql语句的where 条件

时间:2022-01-09 02:50:58

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;


public class A
{
    public A(string arg)
    {
        field = arg;
    }
   
    public string field
    {
        get;
        set;
    }
}

public partial class test : System.Web.UI.Page
{

    //传入字段名称和字段值进行查询
    private void LinqDynamicQuery(string fieldname, string fieldvalue)
    {
        List<object> o = new List<object>();
        o.Add(new A("abcd"));
        o.Add(new A("abcd123"));
        o.Add(new A("abcd245"));
        o.Add(new A("3222bcd"));

        var qry = from p in o
                  where System.ComponentModel.TypeDescriptor.GetProperties(p)[fieldname].GetValue(p).ToString().Contains(fieldvalue)
                  select p;
        System.Diagnostics.Debug.Assert(false, qry.Count().ToString());
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        LinqDynamicQuery("field", "abc");
    }
}