您的位置:首页 > 数据库

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

2012-10-11 10:58 1066 查看
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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: